C++ 入门 5 版 : count reference and underlying pointers

标签 c++ c++11 shared-ptr

在 C++ 入门第 5 版中。第12章std::shared_ptr据说:

p = q;

pqshared_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
  • 为什么sp1sp2具有相同的use_count?上面说过,赋值会减少 p 的引用计数并增加 q 的计数??

  • 此外,我不知道 sp1sp2 中的底层指针除了相同类型之外可以相互转换:

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

我认为 short 可以转换为 int 但为什么它不起作用?据我所知,它与容器类似:容器类型(类型名称和元素类型)必须相同。然后我不明白书中的这一点:“pqshared_ptrs,它们持有可以相互转换的指针”

最佳答案

Why sp1 and sp2 has the same use_count?

您有两个共享指针,sp1sp2,指向同一资源。

因此,两个共享指针都表明该资源的“使用次数”为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*

他的意思是,“在这个例子中,假设pq都是shared_ptr,或者是完全相同的类型,或者至少是可转换类型,这样 = 是合法的”。

关于C++ 入门 5 版 : count reference and underlying pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458017/

相关文章:

c++ - 为什么 std::initializer_list 不是内置语言?

c++ - 在包含共享指针列表的共享指针后面复制对象

C++共享指针问题

c++ - linux 到 windows C++ 字节数组

c++ - 为什么 qmake 在这种情况下添加 -O1 和 -O2 优化标志?

c++ - std::set::insert() 可以调用赋值运算符吗?

c++ - 为什么 is_default_constructible<Class>::value 在同一类范围内失败

c++ - 如何将具有多个空字符的字符串复制到字符串流?

c++ - 删除自身的对象的线程安全实现

c++ - 成员 std::future 防止 boost::shared_ptr 超出范围