智能指针weak_ptr主要用来协助shared_ptr。不参与引用计数,但是有以下好处:
1 打破递归的依赖关系
2 使用一个共享的资源但是不要所有权,不添加引用计数
3 避免悬空指针。
使用方法有二:
// 方法一
boost::shared_ptr<std::string> sp(new std::string("method1");
// 从shared_ptr构建出来
boost::weak_ptr<std::string>wp(sp);
// 再从shared_ptr获取回去
boost::shared_ptr<std::string> p = wp.lock();
// 方法二
boost::shared_ptr<std::string> sp(new std::string("method1");
// 从shared_ptr构建出来
boost::weak_ptr<std::string>wp(sp);
// 再从shared_ptr获取回去
boost::shared_ptr<std::string> p(wp);
注意:各个智能指针都设计的尽量与STL兼容,但是还有一些问题。比如equal_to中比较string的示例就会导致出错。