Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually calling destructor before delete

auto obj = new Object;
obj->~Object();
delete obj;

I know it's unusual, but is it defined behavior? Can it cause any surprising problems?

like image 565
Anonymous Entity Avatar asked Apr 29 '26 08:04

Anonymous Entity


2 Answers

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 object
  • delete 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

like image 171
WhiZTiM Avatar answered May 02 '26 02:05

WhiZTiM


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.

like image 29
Jesper Juhl Avatar answered May 02 '26 03:05

Jesper Juhl