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

R.24: Use?std::weak_ptr?to break cycles of?shared_ptrs
R.24:?使用std::weak_ptr打破share_ptrs造成的循環(huán)
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依靠使用計數(shù)動作,而循環(huán)構(gòu)造(例如相互持有shared_ptr,譯者注)可能導(dǎo)致計數(shù)永遠不歸零,因此我們需要一種機制打破這種循環(huán)。
Example(示例)
#include
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_;
};
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:很多人說“打破循環(huán)”,我卻覺得“暫時分享所有權(quán)”才是關(guān)鍵)???(BS:打破循環(huán)是必須做的事,臨時分享所有權(quán)是做這件事的方法。你可以簡單地使用另外一個shared_ptr“暫時分享所有權(quán)”。
Enforcement(實施建議)
??? probably impossible. If we could statically detect cycles, we wouldn't need?weak_ptr
??? 差不多不可能。如果你能靜態(tài)檢查到循環(huán),我們將不需要weak_ptr。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r23-use-make_unique-to-make-unique_ptrs
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
