vendredi 18 octobre 2019

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."

Aucun commentaire:

Enregistrer un commentaire