C ++,在基类上调用delete会导致?

时间:2013-10-28 10:39:53

标签: c++ inheritance

我有两个与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”会发生什么?

谢谢。

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

首先,你没有基类的虚拟析构函数,所以当你调用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
};