Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to explicitly destroy objects in order

I know that when the implicit constructors are provided for you your class members are initialised from left to right and top to bottom. In other words, in the order that they're declared. Then when the class object goes out of scope all members are destructed in reverse order. But if I have to destroy members myself do I have to do it in the exact order that they are listed? For example:

struct Dog {};

struct Animal
{
    Dog* dog1 = new Dog;
    Dog* dog2 = new Dog;
    ~Animal() 
    {
        delete dog2;     // First delete dog2
        delete dog1;     // Then delete dog1
    // Or do I?
    }
};

I think the destructor that's provided is an empty one. So when I hear that the class will call the destructors of its members when it goes out of scope, it doesn't do that in its own destructor, but after it, with code that the compiler generates separately? So for example:

struct Animal
{
     Dog dog1;
     // ~Animal(){}implicitly defined destructor here. dog1 isn't destroyed here
    // But is destroyed here, or after, or something along those lines with separate code that the compiler generates?

};

Thanks.

like image 240
Zebrafish Avatar asked Dec 23 '22 22:12

Zebrafish


2 Answers

But if I have to destroy members myself do I have to do it in the exact order that they are listed?

No, do it in whatever order you like.

But I prefer to match the "automatic" order, to keep from being surprised.

I think the destructor that's provided is an empty one. So when I hear that the class will call the destructors of its members when it goes out of scope, it doesn't do that in its own destructor, but after it, with code that the compiler generates separately?

Basically, yes.

Execution of the destructor body is one part of destruction. Another part is destruction of all the members and bases.

like image 134
Lightness Races in Orbit Avatar answered Dec 26 '22 11:12

Lightness Races in Orbit


Remember that there's a distinction between deleting the object pointed at by a pointer and destroying the pointer itself. C++ will automatically destroy the pointers themselves when the containing object's lifetime ends, and it will do so in the reverse of the order in which they were constructed. You're free to delete those pointers in any order you'd like, depending on how the object is set up.

As a note, if you change from using raw pointers to unique_ptrs, then this would be completely handled for you and there would be no need to even have a destructor at all!

like image 43
templatetypedef Avatar answered Dec 26 '22 10:12

templatetypedef