《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
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
- 《Effective STL》读书笔记五:Item 10 - 11:关于allocator
- effective stl读书笔记 -- Item 6
- effective stl读书笔记 —— Item 19
- effective stl读书笔记 —— Item 1
- effective stl读书笔记 —— Item 2
- effective stl读书笔记 —— Item 3
- effective stl读书笔记 —— Item 4
- effective stl读书笔记 —— Item 5
- effective stl读书笔记 —— Item 6
- 《Effective STL》读书笔记四:Item 6 - 9
- 关于STL Allocator
- 关于STL allocator
- effective stl item 6
- 《Effective STL》读书笔记六:Item 12:对 STL容器的线程安全性抱有现实的期望
- Effective STL 读书笔记 1
- Effective STL 读书笔记 2
- Effective STL 读书笔记 3
- Effective STL 读书笔记 4
- poj 1751 -- Highways (并查集+最小生成树)
- 图解数据结构——排序
- dfs全排列
- Matlab使用Java的数据结构类型
- Struts2源码阅读(三)_Dispatcher&ConfigurationProvider .
- 《Effective STL》读书笔记五:Item 10 - 11:关于allocator
- u3d游戏客户端架构(---)
- 最简单的排序,冒泡排序
- C++中的全局变量使用
- 中国的互联网技术企业何时走向世界
- 放松自我.冬日独游
- 一些感想--关于心无畏惧
- cgroup学习(三)——伪文件
- linux下scp命令详解