Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
Peregring-lk Avatar asked Mar 12 '13 17:03

Peregring-lk


2 Answers

The step (2) is also realized?

Yes, it’s guaranteed. The behaviour is safe, but note that in your case you have no way of safely reclaiming the memory of the object without re-constructing it first via placement-new (unless you overladed operator new for your object and you can thus guarantee how the memory was allocated and use the matching deallocation).

like image 75
Konrad Rudolph Avatar answered Sep 28 '22 17:09

Konrad Rudolph


Let's make a 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;
}

Output:

Start...

~some_class()

~classB()

~classA()

End.

So the all destructors are called and in reverse order.

like image 35
masoud Avatar answered Sep 28 '22 19:09

masoud