【发布时间】:2017-05-12 00:05:41
【问题描述】:
我知道,当为您提供隐式构造函数时,您的类成员会从左到右和从上到下进行初始化。换句话说,按照它们被声明的顺序。然后,当类对象超出范围时,所有成员都以相反的顺序被破坏。但是,如果我必须自己销毁成员,我是否必须按照它们列出的确切顺序进行操作?例如:
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?
};
谢谢。
【问题讨论】:
标签: c++ class struct destructor