lundi 22 octobre 2018

Understanding shared_ptr C++

I have a question, please go through the following simple C++ program,

int main( )
{
 shared_ptr<int> sptr1( new int );
 shared_ptr<int> sptr2 = sptr1;
 shared_ptr<int> sptr3;
 shared_ptr<int> sptr4;
 sptr3 = sptr2;

 cout<<sptr1.use_count()<<endl;
 cout<<sptr2.use_count()<<endl;
 cout<<sptr3.use_count()<<endl;

 sptr4 = sptr2;

 cout<<sptr1.use_count()<<endl;
 cout<<sptr2.use_count()<<endl;
 cout<<sptr3.use_count()<<endl;

 return 0;
}

Output: 3 3 3 4 4 4

How does sptr1 and sptr3 objects know reference count is incremented as it prints 4.

As far as i know reference count is a variable in each shared_ptr object.

Aucun commentaire:

Enregistrer un commentaire