我知道当隐式构造函数为您提供时,您的类成员将从左到右、从上到下进行初始化。换句话说,按照它们被声明的顺序。然后,当类对象超出作用域时,所有成员都会以相反的顺序被销毁。但是如果我必须自己销毁成员,我是否必须按照它们列出的确切顺序进行销毁?例如:
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?
};
感谢您的信任。