cplusplus.co.il

Destructors and placement new

Posted on: 16/08/2009

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.

Advertisements

1 Response to "Destructors and placement new"

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;
a->~A();
delete[] buff;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: