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.
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.
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.
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 ...).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With