《Effective STL》读书笔记五:Item 10 - 11:关于allocator

来源:互联网 发布:淘宝买的保健品 编辑:程序博客网 时间:2024/05/22 02:06
Item 10:了解allocator的惯例和限制
Be aware of allocator conventions and restrictions
  • STL中假设所有相同类型的allocator对象是一样的,即allocator中没有非静态的数据成员。这样假设的原因之一是为了保证list的splice操作之后能正确的destroy相应的对象
  • allocator和operator new的接口不一样,返回值也不一样。
  • 许多的标准容器从不使用它们实例化的allocator来分配内存。例如list<T>中,需要分配的是包含T的ListNode类型的内存,而不是T类型。
  • List中,ListNode的对应的allocator是:Allocator::rebind<ListNode>::other
Item 11:理解定制化allocator的合理用法
Understand the legitimate uses of custom allocators
  • 假设你有一套效仿malloc和free的管理共享堆内存的方法:
void* mallocShared(size_t bytesNeeded);
void freeShared(void *ptr);
若想要将STL容器中的内容保存到该共享内存中,需要编写如下的模板:
template<typename T> class SharedMemoryAllocator {
public:
  …
  pointer allocate(size_type numObiects, const void *localityHint = 0)
  {
     return static_cast<pointer>(mallocShared(numObiects* sizeof(T)));
  }
  void deallocate(pointer ptrToMemory, size_ type numObjects)
  {
    freeShared(ptrToMemory);
  }
  …
};
可以这样使用SharedMemoryAllocator:
typedef vector<double, SharedMemoryAllocator<double> > SharedDoubleVec;
...
{
  SharedDoubleVec v;
  ...
}
  • 第二个例子,假设你有两个堆,Heap1和Heap2:
class Heap1 {
public:
  …
  static void* alloc(size_t numBytes, const void *memoryBlockToBeNear);
  static void dealloc(void *ptr);
  …
};
class Heap2 { ... }; // has the same alloc/dealloc interface
进一步假设你想把STL的内容放置在不同的堆上,你需要编写使用Heap1和Heap2来进行内存管理的allocator:
template<typenameT, typename Heap> SpecificHeapAllocator {
public:
  pointer allocate(size_type numObjects, const void *localityHint = 0)
  {
    return static_cast<pointer> (Heap::alloc(numObjects * sizeof(T),localityHint));
  }
  void deallocate(pointer ptrToMemory, size_type numObjects)
  {
    Heap::dealloc(ptrToMemory);
  }
  …
};
可以使用SpecificHeapAllocator 将容器中的内容聚合到一起:
vector<int, SpecificHeapAIlocator<int, Heap1 > > v; 
set<int, SpecificHeapAllocator<int Heap1 > > s; // put both v's and s's elements in Heap1
list< Widget, SpecificHeapAllocator<Widget, Heap2> > L; 
map< int, string, less<int>, SpecificHeapAllocator<pair<const int, string>, Heap2> > m;// put both L's and m's elements in Heap2


原创粉丝点击