我对析构函数有一些理解上的问题。
在以下示例中:
#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;
}
我得到了以下输出:销毁2 这对我来说完全出乎意料,因为我认为当对象停止存在时,析构函数总是会被调用。
但在这个例子中,停止存在的是对象1,并被对象2替代。但是,与其调用对象1的析构函数,却调用了对象2的析构函数。
有人能解释一下吗?