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();
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:
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With