gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:41:22 27 4
gpt4 key购买 nike

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

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

提前致谢!

最佳答案

标准说

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com