Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 556
Tony Park Avatar asked Dec 10 '22 12:12

Tony Park


1 Answers

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.

like image 99
Alex Budovski Avatar answered May 29 '23 08:05

Alex Budovski