【发布时间】: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