Should I explicitly destroy objects in order

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

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 was provided is empty. Therefore, when I hear that a class will call its member destructors when it goes out of scope, it does not do this in its own destructor, but after it with code that the compiler generates separately? 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?

};

Thank.

+4
4

, , ?

, .

"" , .

, , , . , , , , , , ?

, .

. - .

+5

, , , . ++ , , , . , , .

, unique_ptr s, , !

+3

, , , .

, , , , , , , . shared_ptr . .

+1

Lightness , , . ( ) , , , .

Since the destructor is also a function, you can add instructions to this function that will be executed during the destruction of the object. Then, the destructor will follow these instructions, and then it will continue to delete class members in the reverse order.

For instance:

struct Dog {};

struct Animal
{
    Dog* dog1 = new Dog;
    Dog* dog2 = new Dog;
    int var;

    ~Animal() 
    {
        delete dog1;     // First delete dog1
    }   //delete var and then delete dog2
};

The destructor will execute his body, and then he will begin to remove the remaining elements in the reverse order.

+1
source

Source: https://habr.com/ru/post/1665024/


All Articles