我现在开始学习如何编写分配器,我想编写一个使用提供的固定大小的内存池的简单分配器。
到目前为止,我有:
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;
}
上面给出了以下错误:
request for member 'reserve' in 'v', which is of non-class type 'std::vector<int, PtrAllocator<int> >(PtrAllocator<int>)'
我希望能够以某种方式将ptr
传递给我的分配器,以便std::vector
使用它。
我有什么想法可以做到这一点吗?
编辑:我解决了。我必须使用以下main
:
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;
}
答案 0 :(得分:1)
您不能将指针(在您的情况下是动态的)作为模板参数传递,这是静态的。如果它是静态的,你可以传递指针,例如如果你要使用全局分配的对象。
您可以做的是将指针传递给pool
作为C++ allocators, specifically passing constructor arguments to objects allocated with boost::interprocess::cached_adaptive_pool中指出的构造参数:
在C ++ 0x中,分配器应该能够调用任何构造函数,而不仅仅是复制构造函数[...]
编辑关于您的评论:重点是,分配器分配内存但不初始化它。因此,您只能控制,例如内存放置或至少一些基本初始化(设置0或其他)。要初始化内存,必须构造一个对象。为此,您可以实现construct
,因为C ++ 11接受一系列参数,请参阅here,here和here。或者,您可以使用new
/ delete
进行构建和分配here。