在多重继承中使用operator

在多重继承中使用operator

本文介绍了在多重继承中使用operator delete时,谁调用类的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能听起来太傻了,但是,我找不到具体的答案。

This question may sound too silly, however , I don't find concrete answer any where else.

对于后期绑定的工作原理以及继承中使用的虚拟关键字知之甚少。

With little knowledge on how late binding works and virtual keyword used in inheritance.

与代码示例一样,在继承的情况下,指向在heap和delete运算符上创建的派生类对象的基类指针用于释放内存,只有当基础析构函数被声明为虚函数时,才会按顺序调用derived和base的析构函数。

As in the code sample, when in case of inheritance where a base class pointer pointing to a derived class object created on heap and delete operator is used to deallocate the memory , the destructor of the of the derived and base will be called in order only when the base destructor is declared virtual function.

现在我的问题是:

1)当base的析构函数不是虚拟的时,为什么只有在使用delete运算符的情况下才会出现不调用派生dtor的问题,为什么不在下面给出的情况下:

1) When the destructor of base is not virtual, why the problem of not calling derived dtor occur only when in case of using "delete" operator , why not in the case given below:


derived drvd;
base *bPtr;
bPtr = &drvd; //DTOR called in proper order when goes out of scope.

2)当使用delete运算符时,谁负责调用析构函数班上?操作员删除将有一个实现调用DTOR?或编译器写一些额外的东西?如果运算符具有实现,那么它看起来如何,[我需要示例代码如何实现它]。

2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented].

3)如果在此示例中使用了虚拟关键字,那么操作员删除现在如何知道要调用哪个DTOR?

3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call?

Fundamentaly我想知道谁在使用删除时调用了类的dtor。

Fundamentaly i want to know who calls the dtor of the class when delete is used.

<h1> Sample Code </h1>

class base
{
    public:
    base(){
       cout<<"Base CTOR called"<<endl;
    }

    virtual ~base(){
       cout<<"Base DTOR called"<<endl;
    }
};

class derived:public base
{
    public:
        derived(){
            cout<<"Derived CTOR called"<<endl;
        }

    ~derived(){
            cout<<"Derived DTOR called"<<endl;
     }
};

我不确定这是否重复,我在搜索中找不到。

I'm not sure if this is a duplicate, I couldn't find in search.

int main()
{
base * bPtr = new derived();

int main(){ base *bPtr = new derived();

delete bPtr;// only when you explicitly try to delete an object
return 0;

}

推荐答案

编译器生成所有必要的代码,以正确的顺序调用析构函数,无论是堆栈对象还是超出范围的成员变量,还是要删除的堆对象。

The compiler generates all necessary code to call destructors in the right order, whether it be a stack object or member variable going out of scope, or a heap object being deleted.

这篇关于在多重继承中使用operator delete时,谁调用类的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:38