Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
Stackoverflow user Avatar asked Oct 22 '18 09:10

Stackoverflow user


People also ask

What is use of shared_ptr in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

Should I use unique_ptr or shared_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Is shared_ptr copy thread-safe?

std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).

Do you need to delete shared_ptr?

The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.


1 Answers

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).

like image 117
Vittorio Romeo Avatar answered Oct 08 '22 23:10

Vittorio Romeo