Re: question regarding the shared_ptr use_count
On Sunday, February 2, 2014 7:12:57 PM UTC-6, 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;
}
p1 use_count = 1
p2 use_count = 2
second p1 use_count = 2 <<< ???
....
Please let me know where my understanding is going wrong?
Perhaps it useful to have it explicitly pointed out: the reference count is associated with the shared object, not with the shared pointers.
Initial:
p1 refers to object1, whose count==1
p2 refers to object2, whose count==1
Change p1 to refer to what p2 refers to
p1=p2
(Notice, when p1 changes what it points to, the refcount
goes down on the old object, and up on the new one. Afterall,
p1 no longer points to the old object so its refcount must
change!)
Result:
object1 destroyed (no references)
p2 still refers to object2, whose count==2
p1 also refers to object2, whose count==2
Notice that p1 and p2 both end up referring to the same underlying
object, so they both report the same reference count.
Chris