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

时间:2015-07-20 04:22:12

标签: c++ destructor

考虑下面的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

一个析构函数。 number = 2

一个析构函数。 number = 2

注意最后一行的复制。我理解(并且讨厌)为什么默认构造函数由main中的第一行调用,但是从不调用该实例的析构函数。相反,第二个实例的析构函数被隐式调用两次。为什么?变量'number'如何在数字= 2时保持不变?析构函数将其设置为0.就像垃圾收集器试图删除默认构造函数创建的实例但是命中第二个的旧副本一样。这是一个简单的例子,但是当它需要删除指针时,这是一个真正的问题。

1 个答案:

答案 0 :(得分:6)

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)