lundi 31 juillet 2017

What happens when a copy of shared_ptr is made?

I want to understand how the reference count of the managed object in a shared_ptr is affected when a shared_ptr is assigned to another.

I came across the following statement in C++ primer, 5th edition, that:

For example, the counter associated with a shared_ptr is incremented when ... we use it as the right-hand operand of an assignment... The counter is decremented when we assign a new value to the shared_ptr...

As an example its shown there:

auto p = make_shared<int>(42); // object to which p points has one user

auto q(p); // p and q point to the same object
           // object to which p and q point has two users

auto r = make_shared<int>(42); // int to which r points has one user
r = q; // assign to r, making it point to a different address
       // increase the use count for the object to which q points
       // reduce the use count of the object to which r had pointed
       // the object r had pointed to has no users; that object is automatically freed

When I run a similar code, the above is not my observation:

Code:

#include<iostream>
#include<memory>

int main()
{
  std::shared_ptr<int> sh1 = std::make_shared<int>(1);
  std::shared_ptr<int> sh2 = std::make_shared<int>(2);

  sh2 = sh1;

  std::cout << "sh1 use count: " << sh1.use_count() << std::endl;
  std::cout << "sh2 use count: " << sh2.use_count() << std::endl;

  return 0;
}

Output:

sh1 use count: 2

sh2 use count: 2

How can the use_count of sh2 also 2? Should not it be 0 as per the mentioned text above? Am I missing something here?

Aucun commentaire:

Enregistrer un commentaire