Search code examples
c++shared-ptrsmart-pointersreference-counting

Understanding C++ std::shared_ptr


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.


Solution

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

    No, the reference count is stored in a "control block" on the heap. Every shared_ptr instance points to the same "control block" and keeps it alive (until all instances and all weak_ptr instances that share ownership with them are dead).