在 C++ 入门第 5 版中。第12章std::shared_ptr
据说:
p = q;
“p
和 q
是 shared_ptr
,它们保存可以相互转换的指针。递减 p
的引用计数并增加 q
的计数,如果 p
的计数变为 0,则删除 p
的现有内存。”
所以我尝试过这个:
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;
输出:
sp1.use_count(): 1
sp2.use_count(): 0
sp1.use_count(): 2
sp2.use_count(): 2
为什么
sp1
和sp2
具有相同的use_count
?上面说过,赋值会减少p
的引用计数并增加q
的计数??此外,我不知道
sp1
和sp2
中的底层指针除了相同类型之外可以相互转换:std::shared_ptr<int> spi = std::make_shared<int>(0); std::shared_ptr<short> sps = spi; // error
我认为 short
可以转换为 int
但为什么它不起作用?据我所知,它与容器类似:容器类型(类型名称和元素类型)必须相同。然后我不明白书中的这一点:“p
和q
是shared_ptr
s,它们持有可以相互转换的指针”
最佳答案
Why sp1 and sp2 has the same use_count?
您有两个共享指针,sp1
和 sp2
,指向同一资源。
因此,两个共享指针都表明该资源的“使用次数”为2。
<小时/>it is said above that that assignment decrements p's reference count and increments q's count??
如果p
最初指向其他东西就可以了。现在,指向该其他资源的共享指针就少了一个。
I think [
int
] can be converted to [short
] but why it doesn't work?
是的,int
可以转换为short
。也就是说,您可以采用 int
并创建一个新的 short
来保存相同的值(如果它在类型的范围内)。
但是 short
不是 int
,因此如果您有 int
,则不能使用 short*
指向它。
这与共享指针无关。尝试一下:
int x = 0;
short* y = &x;
你会发现你不能拥有这个,也没有意义。
<小时/>As I may know it is similar to container: The containers types (type name and element type) must be the same
不,这与此没有太大关系。
<小时/>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."
某些指针是可转换的,例如Derived*
到Base*
。
他的意思是,“在这个例子中,假设p
和q
都是shared_ptr
,或者是完全相同的类型,或者至少是可转换类型,这样 =
是合法的”。
关于C++ 入门 5 版 : count reference and underlying pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458017/