【发布时间】:2014-01-01 10:22:13
【问题描述】:
我现在开始学习如何编写分配器,我想编写一个使用提供的固定大小内存池的简单分配器。
到目前为止,我有:
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;
}
【问题讨论】:
标签: c++