所以在下面的例子中,我们让 classFoo
用*this = Foo()
. 我很高兴我刚刚测试了这个,因为在这种情况下,旧的析构函数Foo
不会被调用。我猜那是因为默认赋值运算符只是使用memcpy
......但作为一个语言设计问题......你为什么不让默认赋值运算符首先破坏分配对象以防止意外?
#include <iostream>
using namespace std;
class MustBeDestroyed //(for some reason not shown here)
{
public:
int i;
MustBeDestroyed(int i) : i(i) {}
~MustBeDestroyed() { cout << "destroyed contained class " << i << endl; }
};
class Foo
{
public:
MustBeDestroyed x;
Foo(int y) : x(y) {}
void replace_myself(int y) { Foo f(y); *this=f; }
void print() { cout << "This is outer/inner class " << x.i << endl; }
~Foo() { cout << "destroyed outer class " << x.i << endl; }
};
int main()
{
Foo a(1);
a.print();
a.replace_myself(2);
a.print();
return 0;
}