C++ 将数据传递给分配器

C++ 将数据传递给分配器,c++,C++,我现在开始学习如何编写分配器,我想编写一个简单的分配器,它使用提供的固定大小的内存池 到目前为止,我已经: template<typename T> class PtrAllocator : public BasicAllocator<T> { private: T* ptr; public: typedef typename BasicAllocator<T>::pointer pointer;

我现在开始学习如何编写分配器,我想编写一个简单的分配器,它使用提供的固定大小的内存池

到目前为止,我已经:

template<typename T>
class PtrAllocator : public BasicAllocator<T>
{
    private:
        T* ptr;

    public:
        typedef typename BasicAllocator<T>::pointer pointer;
        typedef typename BasicAllocator<T>::size_type size_type;
        typedef typename BasicAllocator<T>::value_type value_type;

        template<typename U>
        struct rebind {typedef PtrAllocator<U> other;};

        PtrAllocator(T* ptr) : ptr(ptr) {}

        pointer allocate(size_type n, const void* hint = 0) {return static_cast<pointer>(&ptr[0]);}
        void deallocate(void* ptr, size_type n) {}
        size_type max_size() const {return 5000;}
};


int main()
{
    int* ptr = new int[5000];
    std::vector<int, PtrAllocator<int>> v(PtrAllocator<int>(ptr));
    v.reserve(100);

    delete[] ptr;
}

您不能将指针(在您的情况下是动态的)作为模板参数(静态的)传递。如果指针是静态的,您可以传递它,例如,如果您要使用全局分配的对象

您可以做的是将指向
pool
的指针作为构造参数传递,如中所述:

在C++0x中,分配器应该能够调用任何构造函数,而不仅仅是复制构造函数[…]


编辑关于您的评论:关键是,分配器分配内存,但不初始化内存。因此,您只能控制例如内存放置或至少一些基本初始化(设置0或其他)。要初始化内存,必须构造一个对象。为此,您可以实现
construct
,因为C++11接受一系列参数,请参见和。或者,您可以使用
new
/
delete
进行如上所述的构造和分配。

并非所有指针都是动态的。您可以将全局变量的地址传递给模板。可以,但他不想全局创建他的池。对不起,我应该指出更多。进行了编辑。我编辑了我的帖子。我试过你说的了。我不知道如何通过
std::vector
构造将任何内容传递给分配器。我已经知道了。我接受了你的回答。这不是我想要的,但我把我的发现添加到了OP中。
request for member 'reserve' in 'v', which is of non-class type 'std::vector<int, PtrAllocator<int> >(PtrAllocator<int>)'
int main()
{
    int* ptr = new int[5000];
    PtrAllocator<int> alloc = PtrAllocator<int>(ptr); //declared on a separate line :l
    std::vector<int, PtrAllocator<int>> v(alloc);
    v.resize(100);

    delete[] ptr;
}