Placement new

To use placement new, you need to #include <new>.

If the object is created on top of another object of the same class, call the original object’s destructor first. When the object goes out of scope its destructor will be called.

If the new object is created in another memory area, call the destructor at the end, as the scoped destructor will not be called, and then delete the memory being used if necessary.

#include <iostream>
#include <new>

class X
    X() { std::cout << "X constructor: " << this << "\n"; }
    ~X() { std::cout << "X destructor: " << this << "\n"; }

int main()
    X x;
    new (&x) X;
    char* mem = new char[sizeof(X)];
    std::cout << "mem: " << static_cast<void*>(mem) << "\n";
    X* px = new(mem) X;
    delete[] mem;
X constructor: 0x7ffc3dcc460f
X destructor: 0x7ffc3dcc460f
X constructor: 0x7ffc3dcc460f
mem: 0x1533010
X constructor: 0x1533010
X destructor: 0x1533010
X destructor: 0x7ffc3dcc460f