【问题标题】:Why is object 'destructed' twice? [duplicate]为什么对象被“破坏”两次? [复制]
【发布时间】:2014-09-17 16:15:31
【问题描述】:

在下面的代码中,a 的析构函数被调用了两次,第一次调用似乎被忽略了:

struct A1
{
    int A;
    A1(int a=0) : A(a) { std::cout << "ctor: " << A << "\n"; std::cout.flush(); }
    ~A1() { std::cout << "dtor: " << A << "\n"; std::cout.flush(); }
};


int main()
{
    A1 a(1), *pa=new A1(2), *pb=new A1(3);

    a.~A1();
    pa->~A1();
    delete pb;
    std::cout << "'destructed' a.A = " << a.A << "\n"; std::cout.flush();

    return 0;
}

输出:

ctor: 1
ctor: 2
ctor: 3
dtor: 1
dtor: 2
dtor: 3
'destructed' a.A = 1
dtor: 1

这里发生了什么?

【问题讨论】:

  • 您有未定义的行为。当a 超出范围时,将调用其析构函数。此外,当a 处于销毁状态时,您将打印a.A
  • @40two:感谢链接 - 我使用了错误的搜索词,我自己没有找到。

标签: c++ destructor


【解决方案1】:

除非你真的知道你在做什么,否则你永远不应该直接调用对象的析构函数。相反,当您 delete 一个对象(使用 new 分配)或超出范围时,允许调用析构函数。

在您的情况下,a.~A1(); 将导致未定义的行为,因为当a 超出范围时,您将再次调用析构函数。

【讨论】:

  • 谢谢你的回答,但上面 40two 提供的链接表明这个问题是一个骗局,我会要求删除它 - 很抱歉失去代表...
  • @slashmais:不用担心。上网点没那么重要。
  • @slashmais 不要删除问题。重复的事实并不重要,也许将来的一些读者会发现您的问题比我发布的问题更合适:)。
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 2014-05-26
相关资源
最近更新 更多