c++ - 为什么在删除派生类对象时调用基类析构函数(虚拟)?

标签 c++ inheritance destructor

析构函数(当然还有构造函数)和其他成员函数之间的区别在于,如果常规成员函数在派生类中具有主体,则仅执行派生类中的版本。而在析构函数的情况下,派生版本和基类版本都会被执行?

很高兴知道在析构函数(可能是虚拟的)和构造函数的情况下究竟发生了什么,即使删除了最派生的类对象,它们也会为其所有基类调用。

提前致谢!

最佳答案

标准说

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant members,the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes. All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes. Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2). A return statement (6.6.3) in a destructor might not directly return to the caller; before transferring control to the caller, the destructors for the members and bases are called. Destructors for elements of an array are called in reverse order of their construction (see 12.6).

同样根据 RAII资源需要与合适对象的生命周期相关联,并且必须调用各个类的析构函数来释放资源。

例如以下代码泄漏内存。

 struct Base
 {
       int *p;
        Base():p(new int){}
       ~Base(){ delete p; } //has to be virtual
 };

 struct Derived :Base
 {
       int *d;
       Derived():Base(),d(new int){}
       ~Derived(){delete d;}
 };

 int main()
 {
     Base *base=new Derived();
     //do something

     delete base;   //Oops!! ~Base() gets called(=>Memory Leak).
 }

关于c++ - 为什么在删除派生类对象时调用基类析构函数(虚拟)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261694/

相关文章:

c++ - 使用未声明的标识符 'buffer'和未使用的变量 'buffer'

c++ - 如果您使用多个 is-a 继承,您是否不想使用相互基类的虚拟继承?

Python:我可以让子类为父类(super class)中定义的运算符返回其自身类型的实例吗?

c++ - 基类没有析构函数,但派生类有。我是否需要寻找与堆无关的陷阱?

c++ std::thread 调用方法从对象原因到调用此类的析构函数

c++ - #define to double - 不同的值?

c++ - 在 Visual Studio 中执行 MSI 命令

c++ - 无法在 Windows 中使用 gcc 链接器链接头文件

python - 如何继承Django变量?

c++ - 为什么 C++ 中的析构函数以与初始化相反的顺序释放内存?