c++ - 我是否必须明确地销毁对象才能

标签 c++ class struct destructor

我知道当为您提供隐式构造函数时,您的类成员是从左到右、从上到下初始化的。换句话说,按照它们被声明的顺序。然后当类对象超出范围时,所有成员都以相反的顺序被破坏。但是如果我必须自己销毁成员,我是否必须按照他们列出的确切顺序来做?例如:

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?
    }
};

我认为提供的析构函数是空的。因此,当我听说该类在超出范围时将调用其成员的析构函数时,它不会在其自己的析构函数中执行此操作,而是在它之后使用编译器单独生成的代码?例如:

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?

};

谢谢。

最佳答案

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

不,按你喜欢的顺序做。

但我更喜欢匹配“自动”顺序,以免感到惊讶。

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?

基本上,是的。

析构函数体的执行是析构的一部分。另一部分是破坏所有成员和基地。

关于c++ - 我是否必须明确地销毁对象才能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349634/

相关文章:

python - OpenCV Python 检测多尺度

c++ - 编辑字符串时接收内存泄漏

c++ - 如何使用 qmake 指定目标 mac os x 版本

python - 获取其他模块中 tkinter 实例的参数

javascript - 在 Javascript 中继承静态属性

java - 将 JcomboBox.getSelectedItem() 连接到类

c++ - 如何在 block 中使用 std::fstream?

c# - 在泛型中使用什么类型进行装箱

c - 如何正确定义结构数组?

c# - 访问修饰符和继承