Assigning one shared_ptr to another

Does one shared pointer assign another to free the memory managed by the latter? Let be

typedef shared_ptr<char> char_ptr_t; char_ptr_t pA(new char('A')); char_ptr_t pB(new char('B')); 

Now, does the following statement free the memory 'A' ?

 /*1*/ pA = pB; 

Or I need to explicitly release it:

 /*2*/ pA.reset(); /*3*/ pA = pB; 

And, is the following code valid to achieve the same?

 /*4*/ pA.reset(pB); //<-- is this valid? Not compiling in MSVC++ 2010, though the standard seems to allow it. 
+4
source share
1 answer

Yes, pA no longer points to char 'A' , so the reference count is decreasing. Since this was the only reference to 'A' , the reference count reaches zero and the char is deleted. It would be very surprising and error prone if you have to explicitly release the link before reassigning.

pA.reset(pB) should not be compiled since reset can only accept a raw pointer, not another shared_ptr .

+3
source

Source: https://habr.com/ru/post/1492499/


All Articles