Does anyone have a tutorial for writing Custom Allocators and Memory Pools for std::vectors and Objects?

Basically I've looked at placement new and I want to know how I can force vectors to use this with my shared memory pointers.

I'm thinking writing a class for it might be much easier but I cannot find tutorials on it. It's so that I can place vectors themselves within my MappedMemory and Objects too.

Writing a custom allocator is just about obeying the interface specified by the C++ standard. It's not really that hard at all. Of course in order to be able to use a custom allocator, you need to specify it in the instantiation of your STL containers, and if it is stateful you need to construct the allocator during the construction of the STL containers.

As for tutorials / guidelines, I think that pretty much every C++ book that talks about the STL has a chapter or section that talks about creating a custom allocator, many of which use the example of a memory pool allocator. Bjarne Stroustrup has a section about allocators in "The C++ Programming Language" with a memory pool example. Then, I wrote a quick and simple example of a no-init allocator as an answer to this SO thread. Scott Meyers talks about allocators in his items 10 and 11 for "Effective STL". Then, you'll find chapters on allocators in books like "C++ Programming with the Standard Template Library" (David R. Musser) (Chapter 24), "The C++ Standard Library: A Tutorial and Reference" (N.M. Josuttis) (Chapter 15), and in "Modern C++ Design: Generic Programming and Design Patterns Applied" (Andrei Alexandrescu) (Chapter 4) (warning: this last book is pretty advanced).

What is hard about creating a custom allocator is making sure it is efficient and robust (reliable), let alone be worth it, because very often the conjunction of OS memory handling mechanisms, the optimizations within the heap implementation, and the optimizations in the standard allocator class (std::allocator) leaves very little room for improvements. The starting point is to take a look at the C++ ISO Standard for the precise definition of what functionality an allocator should provide (the interface specification), and be prepared to comply to it exactly (including no-throw specifications). Also, be very careful about statefulness of the allocator, Stroustrup argues, for example, that there are hardly any legitimate examples of stateful allocators (of course, that doesn't include the global state).

Also, for a working example of a memory pool allocator, look at the Boost.Pool library.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.