1

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

谢谢你。

4

3 回答 3

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

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

于 2013-10-28T10:48:37.097 回答
3

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

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

于 2013-10-28T10:45:20.190 回答
0

首先,您没有基类的虚拟析构函数,因此当您从类调用delete this(这是Base) BigCustomObject 时,Derived它不会被破坏。由于您不再使用对象(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
};
于 2013-10-28T11:00:46.140 回答