我现在开始学习如何编写分配器,并且我想编写一个使用提供的固定大小的内存池的简单分配器。
到目前为止,我有:
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;
}
您不能将指针(在您的情况下将是动态的)作为模板参数(是静态的)传递。如果指针是静态的,则可以传递指针,例如,如果要使用全局分配的对象。
您可以pool
按照在C ++分配器中指出的那样,将指针传递为构造时的参数,特别是将构造函数参数传递给使用boost :: interprocess :: cached_adaptive_pool分配的对象:
在C ++ 0x中,分配器应该能够调用任何构造函数,而不仅仅是复制构造函数[...]
编辑您的评论:重点是,分配器分配内存但不初始化它。因此,您只能控制例如内存的放置或至少一些基本的初始化(设置0或其他)。要初始化内存,必须构造一个对象。为此,您可以实现以下功能construct
,因为C ++ 11接受一系列参数,请参见此处,此处和此处。或者,您可以使用new
/delete
进行此处指出的构造和分配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句