Pergunta

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();
Foi útil?

Solução 2

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.

Outras dicas

You can't call the assignment operator on a destroyed object like you are doing. At least not generally, though it might work with some types. What you can do is this though:

A* object = new A();
object->~A();
// Placement new.
// Constructs a new object in the memory pointed to by object pointer.
// Doesn't allocate memory.
new (object) A(createObject());

You can even use placement new to construct objects of a different type in that memory, as long as they fit. Just be sure of two things:

  1. Don't ever construct an object on top of an already existing object that has not been destructed.
  2. Don't ever call delete on a pointer after you've called the destructor on the object it points to until you've re-construced an object (of the same type) in its place.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top