Re: How to write your own allocator?
I compiled the code snippet above in VC6, it doesn't compile because
the
prototype of function deallocate is wrong: the first argument should
be
void *, not pointer. linux gcc may be a little diffenrent.
however, you should implement the construct, _Charalloc and deallocate
(or their counterparts in linux gcc). when list allocates a new Node,
it calls _Charalloc for memory and construct to init a object T.
when list delete a Node, it calls deallocate. you can replace
allocate<T>::xxx with your own code to implement a custom memory
management
policy(e.g. private heap)
sample code(in VC6):
#include <memory>
#include <list>
#include <iostream>
using namespace std;
template<typename T>
class MyAlloc: public allocator<T>
{
public:
char _FARQ *_Charalloc(size_type _N)
{
cout << "alloc requst size:" << _N << endl;
return allocator<T>::_Charalloc(_N);
}
void construct(pointer p, const T& val)
{
cout << "constuct object:" << val << endl;
allocator<T>::construct(p, val);
}
void deallocate( allocator<void>::pointer ptr,
allocator<T>::size_type count)
{
cout << "Deallocation request: count = " << count
<< endl;
allocator<T>::deallocate(ptr, count);
}
};
int main()
{
typedef list<int, MyAlloc<int> > List_t;
List_t l;
l.push_back(5);
l.push_back(10);
return 1;
}