std::weak_ptr一般使用std::shared_ptr来创建,但std::weak_ptr并不会增加std::shared_ptr的计数:
auto spw = std::make_shared<Widget>(); //spw的引用计数并不会增大 std::weak_ptr wpw(spw);
若上述代码中的spw被析构,则wpw将空悬,可以使用std::weak_ptr的成员函数expired()进行判断。但请注意expired()是非原子操作,所以其结果不一定准确,可能在该函数调用完后,std::shared_ptr空悬。这里提供两种安全获取std::shared_ptr状态的方法:
auto spw = std::make_shared<Widget>(); //spw的引用计数并不会增大 std::weak_ptr wpw(spw); //第一种 //返回std::weak_ptr指向的std::shared_ptr,若wpw为空,则wpw失效悬空 //若wpw不为空,将引用计数+1,保证访问期间不会析构 std::shared_ptr<Widget>spw1 = wpw.lock(); //第二种 //若wpw失效,将抛出异常,否则将引用计数+1,保证访问期间不会析构 std::shared_ptr<Widget> spw3(wpw);
注意对于std::shared_ptr的控制块,只有当其std::weak_ptr的引用次数为0时才会被释放。