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.
19/08/2009 at 23:06
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.