Search code examples
c++destruction

Behaviour of explicit call to destructor


The definition of some_class is:

class some_class
{
   // stuff

public:
   ~some_class()
   {
         delete dynamic_three;
   }

private:
   classA one;
   classB two;
   classC* dynamic_three;
}

When the lifetime of a object ends, its destruction is: (1) to call its destructor and (2) to destroy its subobjects in the same order on which they are declared in the class definition (= position in memory).

But, if I have something like that:

auto* ptr = new some_class();

// more stuff

ptr->~some_class(); // l. X

The step (2) is also realized? I mean, in line X, are destructors of subobjects also called or only is executed the body of the some_class's destructor?


Solution

  • When the lifetime of a object ends, its destruction is: (1) to call its destructor and (2) to destroy its subobjects in the same order on which they are declared in the class definition (= position in memory).

    and (3) the allocated memory is freed.

    The step (2) is also realized?

    Step (2) yes, but not step (3).

    But if you can write

    auto* ptr = new some_class();
    

    note that you can also write

    std::unique_ptr<ptr> ptr (new some_class());
    

    which would call delete for you (of course, only use this if this matches your needs, but use this by default if you are not sure).