Domanda

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?

È stato utile?

Soluzione 3

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).

Altri suggerimenti

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).

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top