Search code examples
c++destructorexplicit-destructor-call

Invoke destructor manually and reuse memory


While I understand that this is probably not the best of ideas, I ask hypothetically:

Is it legal to (i.e. defined behavior) to invoke an object's destructor manually, and then reuse the memory for another object?

Definitions:

class A {
  int a, b, c;
  A() {}
  ~A() {}
}

A createObject() {
  A object;
  return object;
}

Code:

A* object = new A();
// Use object...
object->~A();
*object = createObject();

Solution

  • Calling a destructor explicitly is a legal thing to do - in fact, that's what you do when you use placement new. Initializing an object "in place", when the memory is already allocated, is also a legal thing do do, but you should do it differently: rather than using the assignment operator, you could use this syntax:

    object = new (object) A(); // Placement syntax
    

    The way you did it (with an assignment operator) is incorrect, because you are calling a function (i.e. the assignment operator) on an object the destructor of which has completed.