Destructors and placement new

August 16th, 2009 § 1 Comment

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 Response to Destructors and placement new

  • Sumant says:

    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

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Destructors and placement new at 0x.

meta