【问题标题】:Delete inside destructor call删除内部析构函数调用
【发布时间】:2014-12-27 12:11:00
【问题描述】:

在以下代码中:

class Base {
public:
    virtual ~Base(){}
};

class Derived : public Base
{
    Derived* d;

public:
    ~Derived()
    {    
        delete d;
    }
    Derived():d(NULL){}
};


int main()
{
    Base* b = new Derived;
    delete b;
    return 0;
}

Derived 析构函数内的调用delete d; 会导致析构函数调用中的递归吗?

【问题讨论】:

  • 可以,只要d is != nullptr。否则 delete nullptr; 无效。
  • 取决于d 的初始化方式;如果到this,那么是的,如果到另一个对象(例如在链中),那么可能不是(取决于链)。
  • 是的,确实如此。这是一个典型的链表示例。

标签: c++ destructor delete-operator


【解决方案1】:

实际上没有,除了 main 中的那个之外,没有调用任何析构函数。

Reference on delete

如果表达式不是空指针,则删除表达式调用 被销毁的对象的析构函数(如果有的话),或者 数组的每个元素都被销毁(从最后一个开始 元素到数组的第一个元素)。

这让我想到,既然 d 是 NULL,那么析构函数就不会被调用。 delete 将执行,但会返回而不执行任何重要操作。

这也很容易通过在每个析构函数中添加std::cout 语句来测试

【讨论】:

    【解决方案2】:

    析构函数

     Derived::~Derived() {    
            delete d;
       }
    

    不属于递归,因为 d 是指向不同 Derived 对象的指针,并且与 this(当前对象)不同,因此即使调用 Derived::~Derived(),也会调用不同的对象,并最终在 d 为 NULL 时停止在链中的某个地方。

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 2014-11-16
      • 2013-09-30
      • 1970-01-01
      • 2017-08-28
      • 2013-11-16
      • 2011-11-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多