Search code examples
c++rule-of-three

When assigning in C++, does the object we assigned over get destructed?


Does the following code fragment leak? If not, where do the two objects which are constructed in foobar() get destructed?

class B
{
   int* mpI;

public:
   B() { mpI = new int; }
   ~B() { delete mpI; }
};

void foobar()
{
   B b;

   b = B();  // causes construction
   b = B();  // causes construction
}

Solution

  • The default copy assignment operator does a member-wise copy.

    So in your case:

    {
      B b;      // default construction.
      b = B();  // temporary is default-contructed, allocating again
                // copy-assignment copies b.mpI = temp.mpI
                // b's original pointer is lost, memory is leaked.
                // temporary is destroyed, calling dtor on temp, which also frees
                // b's pointer, since they both pointed to the same place.
    
      // b now has an invalid pointer.
    
      b = B();  // same process as above
    
      // at end of scope, b's dtor is called on a deleted pointer, chaos ensues.
    }
    

    See Item 11 in Effective C++, 2nd Edition for more details.