TITLE: explicitely invoking con/destructors (Newsgroups: comp.lang.c++,comp.std.c++, 9 Aug 98) HUNTER: "Jason Hunter" >Actually, you could still use the placement operator new trick even to >reinitialize an already created object. Just case the object pointer to >void * and then pass it to the new operator. This is what I have done. CLAMAGE: stephen.clamage@sun.com (Steve Clamage) You don't need an explicit cast, since conversions to void* can be implicit. HUNTER: >Are there a set of restriction on where and when you can call a constructor >explicitly on an existing object? CLAMAGE: You are explicitly allowed to destroy an object and create a new object of the same type in its place. Two examples for a type T: void f() { T* p = new T; // heap object p->~T(); // destroy old object new (p) T; // create new object delete p; // destroy new object and return storage T q; // auto object q.~T(); // destroy old object new (&q) T; // create new object // new object destroyed automatically at function end } You must also be aware that from the time the destructor starts to run until the time the new constructor has completed, the object is no longer a T object. In particular, don't modify an object this way from one of its member functions (or base-class member functions). If you create a new object without destroying the old one first, the results are undefined for any program that depends on side effects of the destructor. Suppose T locks a resource, unlocked by the destructor. You need to call the destructor before replacing the old object. If you create a new object of a different type in place of the old one, and if pointers to the object exist, the results are undefined if you treat the old pointer as anything but a void*. Suppose type T has a member function f, and we construct a U object in place of a T object: new (p) U; p->f(); The last line calls T::f on a U object, which can't be good. If f is virtual, it the call itself is likely to crash the program. There are other obvious problems involving size and alignment. If the new type is bigger or has stricter alignment requirements, the program is likely to crash. Section 3.8 "Object lifetime" of the standard has more details.