Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared pointers not increasing the use_count

I'm trying to get an idea on how to use std::shared_ptr in C++. But it's pretty confusing and I don't understand how to create multiple shared pointers pointing to the same object. Even the documentation and online material is not very lucid.

Following is a small piece of code I wrote to try and understand std::shared_ptr's behavior:

#include <iostream>
#include <memory>
using namespace std;

class Node
{
public:
    int key;
    Node()
    {
        key = 0;
    }
    Node(int k)
    {
        key = k;
    }
};

int main()
{
    Node node = Node(10);

    shared_ptr<Node> ptr1((shared_ptr<Node>)&node);
    cout << "Use Count: " << ptr1.use_count() << endl;

    // shared_ptr<Node> ptr2=make_shared<Node>(node);//This doesn't increase use_count
    shared_ptr<Node> ptr2((shared_ptr<Node>)&node);
    cout << "Use Count: " << ptr2.use_count() << endl;

    if (ptr1 == ptr2)
        cout << "ptr1 & ptr2 point to the same object!" << endl;

    if (ptr1.get() == ptr2.get())
        cout << "ptr1 & ptr2 point to the same address!" << endl;

    cout << "ptr1: " << ptr1 << "  "
         << "ptr2: " << ptr2 << endl;
    return 0;
}

Based on the output I got, both ptr1 and ptr2 pointed to the same Node object but the use_count is 1 for both of them. Even using std::make_shared doesn't work and the program crashes before exiting.

Can you please tell me what I'm doing wrong? And how to create multiple shared_ptr(s) that are pointing to the same object.

like image 626
Dee Jay Avatar asked Dec 13 '22 18:12

Dee Jay


1 Answers

The use_count won't increase when you create shared_ptrs separately (including using make_shared), they're not shared at all. The created shared_ptr knows nothing about other shared_ptrs and the pointers being managed, even the pointers might happen to be the same (note that it might lead to multiple destruction).

You need to tell which shared_ptrs should be shared; the use_count increases when you create shared_ptr from another shared_ptr. e.g.

shared_ptr<Node> ptr1 = make_shared<Node>(10);
cout<<"Use Count: "<<ptr1.use_count()<<endl; // 1

shared_ptr<Node> ptr2(ptr1);
cout<<"Use Count: "<<ptr2.use_count()<<endl; // 2
cout<<"Use Count: "<<ptr1.use_count()<<endl; // 2

BTW: As the comments suggusted, it's dangerous to make a shared_ptr managing a pointer to &node, which points to an object allocated on stack. The following code might match your intent closely.

Node* node = new Node(10);

shared_ptr<Node> ptr1(node);
cout<<"Use Count: "<<ptr1.use_count()<<endl; // 1

shared_ptr<Node> ptr2(ptr1);
cout<<"Use Count: "<<ptr2.use_count()<<endl; // 2
cout<<"Use Count: "<<ptr1.use_count()<<endl; // 2
like image 134
songyuanyao Avatar answered Jan 11 '23 16:01

songyuanyao