Does assigning one shared pointer to another free the memory managed by the latter? Let
typedef shared_ptr<char> char_ptr_t;
char_ptr_t pA(new char('A'));
char_ptr_t pB(new char('B'));
Now, does the below statement free the memory of 'A'
?
/*1*/ pA = pB;
Or do I need to explicitly free it:
/*2*/ pA.reset();
/*3*/ pA = pB;
And, is the following code valid for achieving the same?
/*4*/ pA.reset(pB); //<-- is this valid? Not compiling in MSVC++ 2010, though the standard seems to allow it.
shared_ptr is also helpful in C++ Standard Library containers when you're using algorithms that copy elements. You can wrap elements in a shared_ptr , and then copy it into other containers with the understanding that the underlying memory is valid as long as you need it, and no longer.
Copying a shared_ptr involves copying its internal state object pointer and changing the reference count. Moving it only involves swapping pointers to the internal reference counter, and the owned object, so it's faster.
A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .
When you copy a std::shared_ptr in a thread, all is fine. At first to (2). By using copy construction for the std::shared_ptr localPtr, only the control block is used. That is thread-safe.
Yes, pA
does not point to the char 'A'
anymore, so the reference count is decremented. As it was the only reference to 'A'
, the reference count reaches zero and the char is deleted. It would be highly surprising and error-prone if you'd have to explicitly release the reference before reassignment.
pA.reset(pB)
should not compile, as reset
can only take a raw pointer, not another shared_ptr
.
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