繁体   English   中英

为什么在同一对象上隐式调用析构函数两次?

[英]why is a destructor IMPLICITLY called twice on same object?

考虑以下c ++代码段及其下面的输出。

#include <iostream>
using namespace std;

class One {
public:
    One(int num);
    One();
    ~One();
private:
    int number;
};

One::One(int num) {
    number = num;
    cout << "One constructor number = " << number << endl;
}

One::One() {
    number = 0;
    cout << "default One constructor\n";
}

One::~One() {
    cout << "One destructor. number = " << number << endl;
    number = 0;
}

int main() {
    One uno;
    uno = One(2);
    return 0;
}

默认一个构造函数

一个构造函数数= 2

一个破坏者。 数= 2

一个破坏者。 数= 2

请注意最后一行的复制。 我理解(讨厌)为什么主构造函数的第一行调用默认构造函数,但从未调用该实例的析构函数。 相反,第二个实例的析构函数被隐式调用两次。 为什么? 变量“数字”如何能够在数字= 2时保持不变? 析构函数将其设置为0。这就像垃圾回收器试图删除默认构造函数创建的实例,但击中了2nd的旧副本一样。 这是一个简单的示例,但是当涉及到删除指针时,这是一个真正的问题。

One uno;   // Create a default One instance - default constructor called.
uno = One(2); // Create a temporary One instance - number constructor called and prints 2.
              // Assign temporary to uno - uno now has the number 2.
              // Destroy temporary One instance - destructor called and prints 2.
return 0;
// uno destroyed. It has the number 2, so this also prints 2.

或者,就您看到的输出而言:

default One constructor // from uno construction
One constructor number = 2 // from temporary One(2) construction
One destructor. number = 2 // from temporary One(2) destruction
One destructor. number = 2 // from uno destruction (since number has changed)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM