C++,在基类上调用删除会导致

C++, Calling delete on Base Class results in?

本文关键字:删除 调用 基类 C++      更新时间:2023-10-16

我有两个与以下代码相关的问题C++:

class Base
{
public:
    virtual bool deleteMe()
    { 
        delete this;
        return true;
    }
};
class Derived: public Base
{
public:
    void setBCO(const BigCustomObject& t_BCO)
    { m_BCO=t_BCO;}
    BigCustomObject m_BCO;
};

int main()
{
    Derived *pDerived = new Derived();
    //insertint the "BigCustomObject" by new or local copy makes no difference, or?
    //Because the "setBCO(){m_BCO=t_BCO;}" calls the copy operator anyway, or?
    pDerived->setBCO( ... );
    bool checkDel = pDerived->deleteMe();
    //bool checkDel = ((Base*)pDerived)->deleteMe(); //Does this make any difference?
    std::cout<<checkDel;
}

1.) deleteMe() 函数在删除自己的对象后怎么可能返回一个值???

2.) 当仅删除基本对象时,派生对象中的"BigCustomObject"会发生什么情况?

谢谢。

  1. 为其执行代码的对象仅用作this指针(以及非限定成员名称的隐式容器)。它与可执行代码本身没有任何关系,因此可以正常继续执行。但是,如果deleteMe()在删除后尝试访问this的任何数据成员,则会遇到麻烦。

  2. 在您的情况下,它可能已泄露。从技术上讲,代码具有未定义的行为,因此任何事情都可能发生。原因是Base没有虚拟析构函数,因此未定义通过指向基类的指针删除派生对象。但是,如果Base有一个虚拟析构函数,它将正常工作 - Derived的析构函数将被调用(通过虚拟调度),而虚拟调度又会调用BigCustomObject的析构函数来销毁m_BCO然后调用Base的析构函数。

1)代码不会仅仅因为对象的内存而自毁。它只是意味着成员变量引用的数据将是无效的。

2)我猜BigCustomObject没有被正确破坏,因为Base没有虚拟析构函数。

首先,基类没有虚拟析构函数,因此当您调用delete this(这是Base)时Derived类中的 BigCustomObject 不会被销毁。此外,函数的执行仍然可以,因为您不再使用对象(this)。

您的问题的答案在示例代码的注释中:

class Base
{
public:
    virtual bool deleteMe()
    { 
        this->some_member = 0;//valid
        delete this; 
        //from here on everything you do you can is ok if you don't touch `this`
        //for example:
        //this->some_member = 0;//this is not safe since the object this is already destroyed
        return true;
    }
    virtual ~Base()
    {
        //virtual means that Dirived class has it's destructor called before this one does
    }
    int some_member;//member added to illustrate the lifetimeo of base class
};