Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning one shared_ptr to another

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.
like image 454
winterlight Avatar asked Jul 20 '13 19:07

winterlight


People also ask

Can shared_ptr be copied?

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.

Can you move a shared_ptr?

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.

Can shared_ptr be Nullptr?

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 .

Is copying shared_ptr thread safe?

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.


1 Answers

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.

like image 193
JohannesD Avatar answered Nov 15 '22 21:11

JohannesD