C++核心準則R.24: 使用std::weak

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(示例)

<code>#include <memory>

class bar;

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

class bar
{
public:
explicit bar(const std::weak_ptr& 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 back_reference_;
};
/<memory>/<code>

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


覺得本文有幫助?請分享給更多人。

關注微信公眾號【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!

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


分享到:


相關文章: