Explicit destructor call behavior

Definition some_class:

class some_class
{
   // stuff

public:
   ~some_class()
   {
         delete dynamic_three;
   }

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

When the lifetime of an object ends, its destruction: (1) calls its destructor and (2) destroys its subobjects in the same order in which they are declared in the class definition (= position in memory).

But if I have something like this:

auto* ptr = new some_class();

// more stuff

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

Also step (2) is implemented? I mean, in line X, are destructors of subobjects also called, or are they just executing the body of the destructor some_class?

+5
source share
3 answers

When the lifetime of an object ends, its destruction: (1) calls its destructor and (2) destroys its subobjects in the same order in which they are declared in the class definition (= position in memory).

and (3) freed memory is freed.

Also step (2) is implemented?

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());

delete (, , , , ).

+1

(2)?

, . , , , - ( operator new , , ).

+2

Test:

class classA
{
public:
    ~classA() { cout << "~classA()" << endl; }
};

class classB
{
public:
    ~classB() { cout << "~classB()" << endl; }
};

class some_class
{
public:
    ~some_class() { cout << "~some_class()" << endl; }

private:
    classA one;
    classB two;
};

int main()
{
    cout << "Start..." << endl;

    auto* ptr = new some_class();

    ptr->~some_class();

    cout << "End." << endl;
}

Conclusion:

Start ...

~ some_class ()

~ ClassB ()

~ CLASSA ()

End.

So, all destructors are called in the reverse order.

+2
source

All Articles