R.24: 使用std::weak_ptr打破share_ptrs造成的循环
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_;
};
??? (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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!