在C ++继承中,当指向对象的指针对象指向派生类时,不调用派生类析构函数 [英] In C++ Inheritance, Derived class destructor not called when pointer object to base class is pointed to derived class
问题描述
我是新手,我知道这是一个非常基本的概念,可能也是一个重复。
现在是真的,一旦一个构造函数被调用它的相应的析构函数必须被调用?
[在Dev C ++上运行的代码]
I am newbie and I know this is a very basic concept and might be a duplicate too. Is it now true that once a constructor is called it's corresponding destructor has to be called ? [code run on Dev C++]
class Base
{
public:
Base() { cout<<"Base Constructor\n";}
int b;
~Base() {cout << "Base Destructor\n"; }
};
class Derived:public Base
{
public:
Derived() { cout<<"Derived Constructor\n";}
int a;
~Derived() { cout<< "Derived Destructor\n"; }
};
int main () {
Base* b = new Derived;
//Derived *b = new Derived;
delete b;
getch();
return 0;
}
GIVES OUTPUT
GIVES OUTPUT
Base Constructor
Derived Constructor
Base Destructor
推荐答案
您的代码有未定义的行为。基类的析构函数必须为 virtual
,以便具有定义的行为。
Your code has undefined behavior. The base class's destructor must be virtual
for the following to have defined behavior.
Base* b = new Derived;
delete b;
从C ++标准:
5.3.5删除
5.3.5 Delete
3在第一个选择(删除对象)中,如果
操作数的静态类型不同于动态类型,静态类型应该是操作数动态类型的基类,静态类型应具有虚拟析构函数或行为未定义。
3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
所以在你的情况下,静态类型是 Base
,动态类型是 Derived
。所以 Base
的析构函数应该是:
So in your case, the static type is Base
, and the dynamic type is Derived
. So the Base
's destructor should be:
virtual ~Base() {cout << "Base Destructor\n"; }
这篇关于在C ++继承中,当指向对象的指针对象指向派生类时,不调用派生类析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!