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.
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.)
You have not leaked memory. The memory for the first int object will be deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With