简体   繁体   中英

TCMalloc Allocator for STL

I want to use TCMalloc with STL containers, so I need an allocator built with TCMalloc (like tbb_allocator with TBB malloc). I cannot find any anything TCMalloc documentation (if it is called a documentation). So I start to explore the header files and find a class called STL_Allocator . But something is not clear to me. Quotation from 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.

And the definition of STL_Allocator template class is:

template <typename T, class Alloc>
class STL_Allocator {
//...
}

I have no idea what that Alloc argument could be. Am I supposed to write a wrapper class for some memory allocation functions? Anyone used TCMalloc?

The STL_Allocator class in TCMalloc is an adapter class: you instanciate it with a (simpler) Alloc class providing Allocate and Free methods as in the comment you quoted, and -voila- you get a class that implements all the requirements for an STL allocator (follow the link for an introductory article on what STL allocators are and how to implement one).

Examples of use include the simple_alloc class that Null Set drafted in another answer , but there's an example in the TCMalloc sources: the MyAllocator class in file memory_region_map.h .

Note, however, that the header file defining STL_Allocator is an internal one and is not installed as part of the public include files of the TCMalloc library.

That said, please note that there is no need to use a custom allocator to benefit from TCMalloc in C++ code: if the standard allocator uses malloc() at some point, you just need to preload or link with TCMalloc and that's it. If you are using the GNU C++ compiler, you can #include <ext/malloc_allocator.h> to use an allocator that simply wraps malloc() with no extra logic.

I don't know if it will work, but try this simple wrap of malloc and free.

#include <cstdlib.h>

struct simple_alloc {
    static void* Allocate(size_t size){
        return malloc(size);
    }
    static void Free(void* ptr, size_t size){
        free(ptr);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM