Search code examples
c++destructorundefined-behaviordelete-operator

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?


Solution

  • 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