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
}

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.


Need Your Help

Error Java.Lang.NullPointer Exception on Android Twitter OAuth

android twitter oauth nullpointerexception

i have some problem, i want to make my application OAuth with twitter account

How do I not raise a Python exception when converting an integer-as-string to an int

python text integer

I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row th...

wrapping C callbacks with C++ lambdas, possible to use template polymorphism?

c++ templates lambda c++11 metaprogramming

Okay, I have posted a few questions lately related to wrapping a C callback API with a C++11-ish interface. I have almost got a satisfying solution, but I think it could be more elegant and need the