In C++ primer 5 Edition. Chapter 12 std::shared_ptr
it is said that:
p = q;
"p
and q
are shared_ptr
s 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
andsp2
has the sameuse_count
? And it is said above that that assignment decrementsp
's reference count and incrementsq
's count?? -
Also I didn't know which case can be the underlying pointers in
sp1
andsp2
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_ptr
s holding pointers that can be converted to one another."
Aucun commentaire:
Enregistrer un commentaire