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

Testing $httpBackend on my controller failing

angularjs jasmine

When mocking $httpBackend, if I respond with an object the expectation fails the test. However if I respond with a string there are no issues.

send an integer from a C client to a Java server

java c sockets

I use this code to send an integer from my Java Client to my Java Server

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.