所以在下面的例子中,我們導致類Foo
用*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;
}
什麼意外?賦值就是這樣 - 爲舊值分配一個新值。 – 2013-05-02 14:47:06
默認賦值運算符不使用memcpy(儘管編譯器優化可能會導致這種情況)。這是一項成員任務。 – huskerchad 2013-05-02 14:48:49
'int i,j;我= 5; j = i;'你是不是說我期望不再使用'i'是明智的?我不同意。 – Fiktik 2013-05-02 14:51:38