FAQ 12.16 How are objects created by placement new destroyed?By explicitly calling the object's destructor. This is about the only time a destructor is called explicitly (see FAQ 20.10). For example, if p is a Fred* that was returned from placement new, *p can be destructed as follows. #include <new> using namespace std; class Fred { public: Fred(int i, int j) throw(); virtual ~Fred() throw(); }; Fred* construct(void* place) throw() { Fred* p = new(place) Fred(42, 42); return p; } void destruct(Fred* p) throw() { p->~Fred(); <-- 1 } void sample() throw() { void* place = (void*) 0xFEEDBABE; Fred* p = construct(place); // ... destruct(p); }
Caution: Do not explicitly call the destructor of an object that will later be automatically destroyed, such as an object on the stack, an object on the heap that will be deleted, or a static object. The only time a destructor should be called explictly is when the programmer is in total control of the storage allocation and lifetime of the object in other words, only with objects initialized by the placement new syntax. |