gpt4 book ai didi

c++ - 了解 use_count 与 shared_ptr

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:16 33 4
gpt4 key购买 nike

我想出了下面的例子

std::shared_ptr<foo> a(new foo());
{
std::shared_ptr<foo> b = a;
std::cout << "before" << b.use_count() << "\n"; //returns 2
b.reset();
std::cout << "after" << b.use_count() << "\n"; //returns 0
}
std::cout << "Finished\n";

现在在上面的代码中,第二个 use_count 语句返回零。在那种情况下,析构函数不应该在打印出 "Finished" 之前被调用。为什么第二条语句中的 use_count 打印为 0 ?我读到 use_count 的定义是:

Returns the number of shared_ptr objects that share ownership over the same pointer as this object (including it).

如果我在使用计数之前执行了一个reset(),这仅仅意味着它的引用计数减少了 1。如果我错了请纠正我。

以上是我的理解,如有错误请指正

std::shared_ptr<foo> a(new foo());   //reference count is 1
{
std::shared_ptr<foo> b = a; //reference count becomes 2
std::cout << "before" << b.use_count() << "\n"; //returns 2 //OK this I understand
b.reset(); //b smart pointer gives up its reference count so now it should be 1.
std::cout << "after" << b.use_count() << "\n"; //This should be 1 why is it 0 ?
}
std::cout << "Finished\n";

所以我的问题是为什么 b.use_count() 返回 0 ?

最佳答案

b.reset(); 之后,b(即不指向任何对象)。

根据标准(引用自N4527 §20.8.2.2.5[util.smartptr.shared.obs])

long use_count() const noexcept;

7 Returns: the number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this is empty.

关于c++ - 了解 use_count 与 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31847540/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com