C++核心準則R.24: 使用std::weak_ptr打破share_ptrs造成的循環

R.24: Use std::weak_ptr to break cycles of shared_ptrs

R.24: 使用std::weak_ptr打破share_ptrs造成的循環

 

Reason(原因)

shared_ptr's rely on use counting and the use count for a cyclic structure never goes to zero, so we need a mechanism to be able to destroy a cyclic structure.

shared_ptr依靠使用計數動作,而循環構造(例如相互持有shared_ptr,譯者注)可能導致計數永遠不歸零,因此我們需要一種機制打破這種循環。

 

Example(示例)

#include <memory>

class bar;

class foo
{
public:
  explicit foo(const std::shared_ptr<bar>& forward_reference)
    : forward_reference_(forward_reference)
  { }
private:
  std::shared_ptr<bar> forward_reference_;
};

class bar
{
public:
  explicit bar(const std::weak_ptr<foo>& back_reference)
    : back_reference_(back_reference)
  { }
  void do_something()
  {
    if (auto shared_back_reference = back_reference_.lock()) {
      // Use *shared_back_reference
    }
  }
private:
  std::weak_ptr<foo> back_reference_;
};

Note(注意)

??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.) ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it. You could "temporarily share ownership" simply by using another shared_ptr.

???(HS:很多人說“打破循環”,我卻覺得“暫時分享所有權”纔是關鍵)???(BS:打破循環是必須做的事,臨時分享所有權是做這件事的方法。你可以簡單地使用另外一個shared_ptr“暫時分享所有權”。

 

Enforcement(實施建議)

??? probably impossible. If we could statically detect cycles, we wouldn't need weak_ptr

??? 差不多不可能。如果你能靜態檢查到循環,我們將不需要weak_ptr。

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r23-use-make_unique-to-make-unique_ptrs


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章