【发布时间】:2013-07-10 20:16:58
【问题描述】:
我对析构函数有一个理解问题。
在以下示例中:
#include <iostream>
using namespace std;
class X{
public:
int id;
X(int id){
this->id = id;
}
~X(){
cout << "destroying " << id;
}
};
int main(){
X a(1);
a = X(2);
while(true);
return 0;
}
我得到以下输出:destroying 2
这完全出乎我的意料,因为我认为析构函数总是会在对象停止存在时被调用。
但在本例中,对象 1 停止存在并被对象 2 替换。但不是调用对象 1 的析构函数,而是调用对象 2 的析构函数。
谁能解释一下?
【问题讨论】:
-
a 仅在 main 返回后停止存在,在此期间它永远不会停止存在,您只能使用 op= 分配给它
标签: c++ destructor