auto obj = new Object;
obj->~Object();
delete obj;
I know it's unusual, but is it defined behavior? Can it cause any surprising problems?
You can only do that if you replace the destroyed object pointed by obj with a new object as per:
auto obj = new Object;
obj->~Object();
new (obj) Object();
delete obj;
Otherwise, you invoke Undefined Behavior.
You should understand that:
new calls operator new to obtain memory, then calls the provided construtor to create the objectdelete calls the destructor of the object, then calls operator delete to "return" memory.EDIT: As Bo Persson pointed out, its not a good idea if you can't provide exception guarantees
It is Undefined Behaviour to cause an objects destructor to be invoked twice. You are not following the rules and the compiler is allowed to do whatever it pleases with your code. Just don't do that.
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