Placement new

suggest change

There are situations when we don’t want to rely upon Free Store for allocating memory and we want to use custom memory allocations using new.

For these situations we can use placement new, which constructs an object in storage the program already has.

For example, if sizeof(int) is 4:

int a4byteInteger;

char *a4byteChar = new (&a4byteInteger) char[4];

This ends the lifetime of a4byteInteger and reuses its storage. That storage is automatic, so there is no matching delete. The program must not call delete on a4byteChar.

The same reuse is possible with dynamically allocated memory:

int *a8byteDynamicInteger = new int[2];

char *a8byteChar = new (a8byteDynamicInteger) char[8];

a8byteChar refers to the dynamic storage allocated for a8byteDynamicInteger. Release that storage with delete[] a8byteDynamicInteger. A plain delete would be undefined, because the allocation was new int[2]. This again assumes sizeof(int) is 4.

Another example for C++ Class

#include <new>

struct ComplexType {
    int a;

    ComplexType() : a(0) {}
    ~ComplexType() {}
};

int main() {
    char* dynArray = new char[256];

    //Calls ComplexType's constructor to initialize memory as a ComplexType
    new((void*)dynArray) ComplexType();

    //Clean up memory once we're done
    reinterpret_cast<ComplexType*>(dynArray)->~ComplexType();
    delete[] dynArray;

    //Stack memory can also be used with placement new
    alignas(ComplexType) char localArray[256]; //alignas() available since C++11

    new((void*)localArray) ComplexType();

    //Only need to call the destructor for stack memory
    reinterpret_cast<ComplexType*>(localArray)->~ComplexType();

    return 0;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents