用于STL的TCMalloc分配器

ali*_*hoo 3 c++ memory-management stl allocator tcmalloc

我想将TCMalloc与STL容器一起使用,所以我需要一个用TCMalloc构建的分配器(就像带有TBB malloc的tbb_allocator).我找不到任何TCMalloc文档(如果它被称为文档).所以我开始探索头文件并找到一个名为的类STL_Allocator.但有些事情对我来说并不清楚.来自stl_allocator.h的报价:

// Generic allocator class for STL objects
// that uses a given type-less allocator Alloc, which must provide:
//   static void* Alloc::Allocate(size_t size);
//   static void Alloc::Free(void* ptr, size_t size);
//
// STL_Allocator<T, MyAlloc> provides the same thread-safety
// guarantees as MyAlloc.
//
// Usage example:
//   set<T, less<T>, STL_Allocator<T, MyAlloc> > my_set;
// CAVEAT: Parts of the code below are probably specific
//         to the STL version(s) we are using.
//         The code is simply lifted from what std::allocator<> provides.
Run Code Online (Sandbox Code Playgroud)

而STL_Allocator模板类的定义是:

template <typename T, class Alloc>
class STL_Allocator {
//...
}
Run Code Online (Sandbox Code Playgroud)

我不知道那个Alloc论点是什么.我是否应该为一些内存分配函数编写一个包装类?有人用过TCMalloc吗?

Ric*_*rri 7

STL_Allocator在TCMalloc类是一个适配器类:你一个(简单)的实例化它的Alloc类,它提供AllocateFree方法在你所引用的评论,-voila-你实现所有对于要求的类 STL分配器(跟随链接有关什么是STL分配器以及如何实现STL分配器的介绍性文章.

使用示例包括Null Set另一个答案中起草的simple_alloc类,但TCMalloc源中有一个示例:文件memory_region_map.h中的类.MyAllocator

但请注意,头文件定义STL_Allocator内部文件,不作为TCMalloc库的公共包含文件的一部分安装.

也就是说,请注意,在C++代码中不需要使用自定义分配器来从TCMalloc中受益:如果标准分配器在某些时候使用malloc(),您只需要预加载或链接TCMalloc即可.如果您正在使用GNU C++编译器,则可以#include <ext/malloc_allocator.h>使用仅包装malloc()而没有额外逻辑的分配器.