Advanced memory allocation in C++

There are several reasons you may want to use different than default memory allocation strategies.

Some of them are:

  • you need to allocate a large number of equally large objects
  • you need fast deallocation
  • you care about memory fragmentation (in game console or embedded system)

Special object construction

Sometimes you need to perform object allocation in a special way, here is a short list which mentions special syntax for "new" operator:

nothrow: performing "new" without exception handling

Normally in case of lack of memory standard library raises std::bad_alloc exception. If you instead want to use own "if" logic, you can use "nothrow" syntax:

MyClass *p;
p = new (std::nothrow) MyClass;
if (!p) {
  cout << "Allocation failed!\n";  

allocation of array of objects without calling constructor

In standard situations when you allocate array of objects you use syntax:

const size_t ARRAY_SIZE = 123;
MyClass *ptr = new MyClass[ARRAY_SIZE];

In that case for each object in array default constructor will be executed. If you want to instead call a constructor with some arguments but you don't want to use malloc, you need to allocate array using global "new" operator:

const size_t ARRAY_SIZE = 123;
MyClass *ptr = static_cast<MyClass *>(operator new[](sizeof(MyClass) * ARRAY_SIZE));

Now, in order to execute selected constructor on already allocated memory, you need to call in-place constructor for each array element - see below.

placement new - call constructor for allocated object

When you need to execute constructor for object which has already memory allocated, use "placement new" syntax. This can be useful in "arena allocator" or object pools.

const size_t ARRAY_SIZE = 123;
MyClass *ptr = static_cast<MyClass *>(operator new[](sizeof(MyClass) * ARRAY_SIZE));

size_t i = ARRAY_SIZE;
while (i-- > 0) { 
  // --> placement new, executes constructor for pre-allocated object pointed by ptr[i] with sample parameters
  new (ptr[i]) MyClass(12, 'a', "test"); 
  // <-- 

Specialized allocation solutions

Malloc replacements

Garbage collection in C++

See also