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

落花浮王杯 提交于 2019-12-03 12:42:25

问题


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.


回答1:


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.)




回答2:


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



来源:https://stackoverflow.com/questions/3697329/question-on-assignment-with-boostshared-ptr-vs-the-reset-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!