So in the following example, we cause class Foo
to replace itself with *this = Foo()
. I'm glad I just tested this because it turns out in this circumstance, the destructor of the old Foo
doesn't get called. I guess that's because the default assignment operator just uses memcpy
... but as a language design question ... why wouldn't you make the default assignment operator destroy the assigned-to object first to prevent accidents?
#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;
}