智能指針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的示例就會導致出錯。