我想到了以下例子。
现在,在上述代码中,第二个
我读到use_count的定义是:
返回与此对象共享所有权的shared_ptr对象数量(包括它本身)。
如果我在use count之前执行了reset(),那就意味着它的引用计数减少了1。如果我错了,请纠正我。
这是我的理解,请纠正我如果我错了。
那么我的问题是,为什么
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对象数量(包括它本身)。
如果我在use count之前执行了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
之后,它与其他人共享了什么? - Mat