Search code examples
c++overloadingnew-operatordelete-operatorallocator

Overloading new and delete vs Custom Allocator


How should I approach custom memory allocation for my class. I have seen both methods used extensively. Using a custom allocator, like all stl containers are doing, which make it part of their type with a template type parameter. Or overload the new and delete functions and possibly placement new and placement delete as well. I have visited and read many questions and answers on both of these techniques, but I can't figure out which one should be used in a particular case. Clearly all the stl containers were designed with a custom allocator in mind. Why not overload new and delete (etc.) instead though, in order to satisfy your memory requirements? It seems to me that overloading new and delete can accomplish everything an allocator could and in fact possibly easier with less hassle. This may be especially true in C++17 which comes with a plethora of possible overloads which can even specify alignment requirements, nothrow tag versions etc.

We are told that in C++ we should generally use new and delete for a typical heap allocation (or more frequently smart pointers, but this isn't a "smart" discussion now, this is low level). But what if we use an allocator to allocate our object instead with .allocate() and then construct with .construct() (I believe the last function is deprecated now though). We would essentially be doing the same thing that new std::string{"Hello"} is doing.

Only thing the C++ Core Guidelines mentions about this matter is this (ie. nothing). I can't find much else really. And what about thread safety and security? I have surmised that (custom) memory management is probably the most important aspect of advanced c++ so I must understand exactly what I'm doing.

My question is which one of the two methods to choose to manage the memory of my own class, implementing a custom memory allocator (like the stl containers), or overloading new, delete, new[], delete[], placement new ... and why? Some other good practices and guidelines of where and when would also be very helpful. Thanks in advance.


Solution

  • Broadly speaking, an Allocator type is used when an object of one type (typically a container) needs to manage memory to hold an object or objects of some other type. Overloading operator new and operator delete within a class is used when objects of that type need some special memory management.