cplusplus.co.il

Destructors and placement new

Posted by: rmn 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.

Advertisement

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:

Gravatar
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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 25 other followers