Re: question regarding the shared_ptr use_count
On 03.02.14 03.09, somenath wrote:
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.
The reference counter is no property of the shared_ptr. It is a property
of the objects where the shared_ptr points to.
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.
shared_ptr instances do not have a reference counter.
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"
The reference counter of *p and *q are modified. p and q do not have
reference counters.
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.
This is exactly what's going on.
cout<<"second p1 use_count ="<<p1.use_count()<<endl;
Please help me to get my understanding correct.
Internally shared_ptr uses helper objects to add the reference counter
to arbitrary objects. So your code effectively does the following:
auto p1 = make_shared<string> (10,'S');
tmp1 = new string#1(10,'S')
tmp2 = new helper_obj#1(1, tmp1)
p1 = shared_ptr(tmp2)
result:
p1 -> helper_obj#1{ counter = 1, content -> string#1{"SSSSSSSSSS"} }
cout<<"p1 use_count = "<<p1.use_count()<<endl;
shared_ptr<string> p2(new string()) ;
tmp1 = new string#2()
tmp2 = new helper_obj#2(1, tmp2)
p2 = shared_ptr(tmp2)
result:
p1 -> helper_obj#1{ counter = 1, content -> string#1{"SSSSSSSSSS"} }
p2 -> helper_obj#2{ counter = 1, content -> string#2{} }
p1 = p2;
++p2->counter
--p1->counter
because p1->counter goes to zero:
delete helper_obj#1
delete string#1
result:
p2 -> helper_obj#2{ counter = 2, content -> string#2{} }
p1 -> helper_obj#2{ counter = 2, content -> string#2{} }
cout<<"p2 use_count = "<<p2.use_count()<<endl;
cout<<"second p1 use_count = "<<p1.use_count()<<endl;
The helper objects cause additional allocations and more importantly an
additional indirection at every access to the stored strings. But they
are required to store arbitrary objects in shared_ptr instances.
Marcel