我正在尝试在cpp中重新创建内置的 vector 类,以获取有关类和内存管理的更多实践。我不断收到一个错误消息,说“ISO C++禁止声明无类型的'分配器'”,我无法弄清楚为什么会这样。有什么我想念的吗?

#include <cstddef>
#include <memory>

template <class T>
class myvector{
public:
    typedef T* iterator;
    typedef const T* const_iterator;
    typedef size_t size_type;

    myvector(){ data = avail = limit = 0; }

    explicit myvector(size_type n, const T& t = T()) { create(n,t); }

    myvector(const myvector& v){  create(v.begin(), v.end());  }

    ~myvector() {  uncreate();  }

    myvector& operator=(const myvector& v)
    {
        if (&v != this){
            uncreate();
            create(v.begin(), v.end());
        }
        return *this;
    }


    T& operator[](size_type i) { return data[i];  }
    const T& operator[](size_type i) const {  return data[i];  }

    iterator begin(){  return data;  }
    const_iterator begin() const{  return data;  }

    iterator end(){  return limit;  }
    const_iterator end() const{  return limit;  }

    size_type size(){  return avail - data;  }

    void push_back(T t)
    {
        if(avail == limit)
            size_type new_size = max(2*(limit-data),ptrdiff_t(1));
            iterator new_data = alloc.allocate(new_size);
            iterator new_avail = uninitialized_copy(data,avail,new_data);
            uncreate();
            data = new_data;
            avail = new_avail;
            limit = data + new_size;
        alloc.construct(avail++,t);
    }
private:
    iterator data;
    iterator avail;
    iterator limit;
    allocator<T> alloc;

    void create(size_type n, const T& t)
    {
        data = alloc.allocate(n);
        limit = avail = data+n;
        uninitialized_fill(data,limit,t);
    }

    void create(const_iterator i, const_iterator j)
    {
        data = alloc.allocate(j-i);
        limit = avail = uninitialized_copy(i,j,data);
    }

    void uncreate()
    {
        if(data){
            iterator it = avail;
            while(it != data) {   alloc.destroy(--it);    }
            alloc.deallocate(data,limit-data);
        }
        data = limit = avail = 0;
    }
};

最佳答案

它应该是std::allocator<T> alloc;,标准库中的所有内容都包含在 namespace std中。

关于c++ - 您如何声明分配器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4559319/

10-16 20:24