Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question on assignment with boost::shared_ptr (vs. the reset() function)

Sorry if this is explicitly answered somewhere, but I'm a little confused by the boost documentation and articles I've read online.

I see that I can use the reset() function to release the memory within a shared_ptr (assuming the reference count goes to zero), e.g.,

shared_ptr<int> x(new int(0));
x.reset(new int(1));

This, I believe would result in the creation of two integer objects, and by the end of these two lines the integer equaling zero would be deleted from memory.

But, what if I use the following block of code:

shared_ptr<int> x(new int(0));
x = shared_ptr<int>(new int(1));

Obviously, now *x == 1 is true, but will the original integer object (equaling zero) be deleted from memory or have I leaked that memory?

It seems to me that this would be an issue of the assignment operator decreasing the shared_ptr's reference count, but a glance at the source code doesn't seem to clear the question up for me. Hopefully someone more experienced or knowledgeable can help me out. Thanks in advance.

like image 656
RandomGuy Avatar asked Sep 13 '10 00:09

RandomGuy


2 Answers

The documentation is fairly clear:

shared_ptr & operator=(shared_ptr const & r); // never throws

Effects: Equivalent to shared_ptr(r).swap(*this).

So it just swaps ownership with the temporary object you create. The temporary then expires, decreasing the reference count. (And deallocating if zero.)


The purpose of these containers is to not leak memory. So no, you don't need to worry about leaking things unless you're trying to mess things up on purpose. (In other words, you probably don't need to doubt Boost knows what they're doing.)

like image 65
GManNickG Avatar answered Nov 15 '22 21:11

GManNickG


You have not leaked memory. The memory for the first int object will be deleted.

like image 37
Brian R. Bondy Avatar answered Nov 15 '22 19:11

Brian R. Bondy