Destructors and placement new

When using placement new operator, destruction isn’t as transparent as usual..

Will the destructor be invoked?

#include <iostream>
using std::cout;
using std::endl;

struct A {
    A () { cout << "constructed." << endl; }
    ~A () { cout << "destructed." << endl; }
    int x; // so the class takes more than (the default) 1byte

int main () {
    // using char isn't as portable as we'd like
    void *buff = new char[sizeof(A)];
    new (buff) A; // placement new
    delete[] buff;

Hint: having used placement new, you are also responsible for (explicitly) destructing that object.

One thought on “Destructors and placement new

  1. In such cases, the destructor of the class should be invoked explicitly. This is one of the rare cases where it is necessary to invoke a destructor manually. Here is how it can be done.

    void *buff = new char[sizeof(A)];
    A *a = new (buff) A;
    delete[] buff;

Leave a Reply