Wednesday, February 5, 2014

question regarding the shared_ptr use_count

Newsgroup: comp.lang.c++

Subject: question regarding the shared_ptr use_count

From: somenath <somenathpal@...>

Date: Sun, 2 Feb 2014 17:12:57 -0800 (PST)



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?







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://ift.tt/1keZz0q

View all the progranning help forums at:

http://ift.tt/1dP9txN

No comments:

Post a Comment