【问题标题】:understanding use_count with shared_ptr用 shared_ptr 理解 use_count
【发布时间】:2015-08-06 05:34:00
【问题描述】:

我想出了下面的例子

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的定义是:

返回共享所有权的 shared_ptr 对象的数量 与此对象相同的指针(包括它)。

如果我在使用计数之前做了一个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 重置后会与其他人分享什么?

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


【解决方案1】:

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

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

long use_count() const noexcept;

7 返回:shared_ptr 对象的数量,包括*this,与*this0共享所有权*this

【讨论】:

    【解决方案2】:

    共享指针是 C++ 中的一个概念,您可以在不同范围内拥有多个指向对象的指针,并且只有在最后一个范围返回之前,您的共享指针才会无效,唯一指针只能使用 std 传递给函数: :move() 由于它的定义,唯一指针意味着对所指向的对象的单一所有权。现在,由于您有一个 share_ptr a(new foo()),然后将其分配给 b,一旦对该 b shared_ptr 类型调用 reset,b 无效并因此返回零,但是如果您执行操作 use_count( ) 在 a 上,重置 b 后会得到 1 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 2020-10-08
      • 2019-10-10
      相关资源
      最近更新 更多