Re: question regarding the shared_ptr use_count
On Monday, February 3, 2014 6:53:44 AM UTC+5:30, Ian Collins wrote:
somenath wrote:
I am not able to understand the behavior of the following program
#include <iostream>
#include<memory>
#include<string>
using namespace std;
int main() {
auto p1 = make_shared<string> (10,'S');
cout<<"p1 use_count = "<<p1.use_count()<<endl;
shared_ptr<string> p2(new string()) ;
p1 = p2;
cout<<"p2 use_count = "<<p2.use_count()<<endl;
cout<<"second p1 use_count = "<<p1.use_count()<<endl;
return 0;
}
Output
++++++++++++++++
p1 use_count = 1
p2 use_count = 2
second p1 use_count = 2
I can understand the first two print. At beginning p1 points to one
string so the reference count is 1. When the statement p1=p2;
executes p2's reference count gets incremented to 2 but at the same
time I was expecting that p1's reference count to be decremented by 1
as p1 would be pointing to p2 now. Please let me know where my
understanding is going wrong?
p1 *is* p2. There are to references (p1 and p2) to the string initially
assigned to p1. Both have to go out of scope for the string to be deleted.
I couldn't follow you. Why p2 would refer to the "string initially
assigned to p1"?
p2 is defined as follows
shared_ptr<string> p2(new string())
So according to my understanding p2 would refer to the empty string.
Then when the statement p1=p2; gets executed p1 also start referring to what ever p2 referring to. So the reference count of p2 will increase and also hoped that p1's reference count to be decremented by 1 but that does not happen.
I think this way because the book I refer for understanding these concept says.
"We can think of shared_ptr as if it has an associated counter,usually referred to as a reference count.
...
...
p=q p and q are shared_ptrs holding pointers that can be converted to one another. Decrements p's reference count and increments q's count; deletes p's existing memory if p's count goes to 0"
But I think it is better to think reference count as the count of pointers pointing to some memory location. In that case according to my program the following statement
p1=p2;
will increase the reference count of the memory location that p2 point as p1 also point to the same location.As p1 also point to the same meory location so when I print p1's reference count it prints the same count as p2.
cout<<"second p1 use_count = "<<p1.use_count()<<endl;
Please help me to get my understanding correct.
--
Somenath