【问题标题】:what does .reset do to a shared_pointer.reset 对共享指针有什么作用
【发布时间】:2014-11-23 01:10:34
【问题描述】:

我想知道.reset() 对共享指针做了什么。 它是像here 提到的那样简单地将共享指针的引用计数减一还是删除对对象的所有引用计数,将计数重置为 0

这是我的代码示例

std::vector<boost::shared_ptr<foo>> vec;
boost::shared_ptr<foo> f(boost::make_shared<foo>()); //ref count 1
vec.push_back(f); //ref count 1
vec.push_back(f); //ref count 3
int a = f.use_count(); //Will return 3
f.reset();        //Will turn the refernece count to 0
vec[1].reset();   //Will reduce the reference count by 1.
a = f.use_count();

我很好奇为什么 f.reset() 会将引用计数变为 0,而 vec[1].reset() 将引用计数减少 1

【问题讨论】:

标签: c++ shared-ptr


【解决方案1】:

它释放当前引用。其他参考不受影响。

【讨论】:

  • @MistyD 在你调用f.reset() 之后,当然 f.use_count() 是0。它没有任何参考!但是如果你打电话给vec[0].use_count(),它应该有正确的号码。
猜你喜欢
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 2011-06-15
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
相关资源
最近更新 更多