我已经获得了一个自定义分配器,它实现了它自己的分配策略,它自己的malloc/free等等.现在,我被要求使用这个自定义分配器和一个STL容器(它是一个向量或其他).我创建了一个类,比如说my_stdAllocator,这是一个符合ISO C++标准的接口.通过这个类我调用我的分配器的方法.例如:
template <class T>
class my_stdAllocator {
// ...other required stuff...
// allocate 'num' elements of type T
pointer allocate(size_type num, const_pointer = 0) {
return static_cast<T*>(MYAllocator::instance()->malloc(num));
}
// deallocate memory at 'p'
void deallocate(pointer p, size_type num=0) {
MYAllocator::instance()->free(p);
}
// initialize allocated memory at 'p' with value 'value'
void construct(pointer p, const T& value) {
::new ((void*)p) T(value);
}
// destroy elements of initialized memory at p
void destroy(pointer p) {
p->~T();
} …Run Code Online (Sandbox Code Playgroud)