title: Why doesn't default assignment operator call the destructor first?
body: <p>So in the following example, we cause class <code>Foo</code> to replace itself with <code>*this = Foo()</code>.  I'm glad I just tested this because it turns out in this circumstance, the destructor of the old <code>Foo</code> doesn't get called.  I guess that's because the default assignment operator just uses <code>memcpy</code> ... but as a language design question ... why wouldn't you make the default assignment operator destroy the assigned-to object first to prevent accidents?</p>
  
  <p><a href="http://codepad.org/9WCo6yZ5">http://codepad.org/9WCo6yZ5</a></p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  class MustBeDestroyed //(for some reason not shown here)
  {
  public:
    int i;
    MustBeDestroyed(int i) : i(i) {}
    ~MustBeDestroyed() { cout &lt;&lt; "destroyed contained class " &lt;&lt; i &lt;&lt; endl; }
  };
  
  class Foo
  {
  public:
    MustBeDestroyed x;
    Foo(int y) : x(y) {}
    void replace_myself(int y) { Foo f(y); *this=f; }
    void print() { cout &lt;&lt; "This is outer/inner class " &lt;&lt; x.i &lt;&lt; endl; }
    ~Foo() { cout &lt;&lt; "destroyed outer class " &lt;&lt; x.i &lt;&lt; endl; }
  };
  
  int main()
  {
    Foo a(1);
    a.print();
    a.replace_myself(2);
    a.print();
    return 0;
  }
  </code></pre>