c++shared-ptr

Count of a shared_ptr when managing the same object


If a shared_ptr is declared twice managing the same object, why does the count not increase to two, since the same object is being managed?

 int i = 1;
 std::shared_ptr<int> p1 = std::make_shared<int>(i);
 std::shared_ptr<int> p2 = std::make_shared<int>(i);
    
 std::cout << p1.use_count() << std::endl;

In the obove the the count is 1, not 2.


Solution

  • You create 2 different pointers, the make_shared() function creates a new pointer, not copies it. To make the p2 pointer refer to the p1 pointer, you must use the copy constructor, and shared_ptr must refer to a pointer in which case a new int is created instead of i:

    std::shared_ptr<int> p1 = std::make_shared<int>(i);
    std::shared_ptr<int> p2 = p1; // copy and increment the counter
    //p1.use_count(); == 2 
    

    in order to refer to the original i you have to:

    int* i = new int (1);
    std::shared_ptr<int> p1(i); // means to refer to an existing pointer
    std::shared_ptr<int> p2 = p1;
    //p1.use_count(); == 2