.reset 对shared_pointer有什么作用

what does .reset do to a shared_pointer

本文关键字:什么 作用 pointer shared reset      更新时间:2023-10-16

我想知道.reset()对共享指针做了什么。它只是将共享指针的引用计数减少 1,如此处所述,还是删除对象的所有引用计数,将计数重置为 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

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