Search code examples
c++c++11shared-ptr

C++ primer 5 edition: count reference and underlying pointers


In C++ primer 5 Edition. Chapter 12 std::shared_ptr it is said that:

p = q;

"p and q are shared_ptrs holding pointers that can be converted to one another. Decrements p's reference count and increments q's count, deletes p's existing memory if p's count goes to 0."

So I've tried this:

std::shared_ptr<int> sp1 = std::make_shared<int>(10);
decltype(sp1) sp2 = nullptr;

std::cout << sp1.use_count() << std::endl;
std::cout << sp2.use_count() << std::endl;

sp2 = sp1;

std::cout << sp1.use_count() << std::endl;
std::cout << sp2.use_count() << std::endl;

The output:

sp1.use_count(): 1
sp2.use_count(): 0
sp1.use_count(): 2
sp2.use_count(): 2
  • Why sp1 and sp2 has the same use_count? And it is said above that that assignment decrements p's reference count and increments q's count??

  • Also I didn't know which case can be the underlying pointers in sp1 and sp2 convertible to each other other than being the same type:

    std::shared_ptr<int> spi = std::make_shared<int>(0);
    std::shared_ptr<short> sps = spi; // error
    

I think short can be converted to int but why it doesn't work? As I may know it is similar to container: The containers types (type name and element type) must be the same. Then I don't understand that point here in the book: "p and q are shared_ptrs holding pointers that can be converted to one another."


Solution

  • Why sp1 and sp2 has the same use_count?

    You have two shared pointers, sp1 and sp2, pointing to the same resource.

    So, both shared pointers indicate that the "use count" of the resource is 2.


    it is said above that that assignment decrements p's reference count and increments q's count??

    It would do if p was originally pointing to something else. You'd now have one fewer shared pointer that points to that other resource.


    I think [int] can be converted to [short] but why it doesn't work?

    Yes, an int can be converted to a short. That is, you can take an int and create a new short that holds the same value (if it's within the range of the type).

    But a short is not an int, so if you have an int, you cannot use a short* to point to it.

    That's regardless of shared pointers. Just try:

    int x = 0;
    short* y = &x;
    

    and you'll see that you can't have this, nor does it make sense to.


    As I may know it is similar to container: The containers types (type name and element type) must be the same

    No, it doesn't have much to do with that.


    I don't understand that point here in the book: "p and q are shared_ptrs holding pointers that can be converted to one another."

    Some pointers are convertible, such as Derived* to Base*.

    He means, "in this example, assume that p and q are both shared_ptrs, either of the exact same type, or at least of convertible type, so that the = is legal".