智能指针+周期+“ - >” [英] Smart pointers + cycles + "->"

查看:117
本文介绍了智能指针+周期+“ - >”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我真的确定我想有指针的循环依赖,循环中的每个对象应该能够使用他的指针(所以它不能weak_ptr)。

Sometimes I'm really sure that I want to have circular dependence of pointers, and every object on cycle should be able to use his pointer (so it can't be weak_ptr).

我的问题是:这是否意味着我的设计不好?

My question is: Does this mean that I have bad design?

如果我想实现图表怎么办?我可以使用智能指针吗?在图中有循环,但是weak_ptr我不能使用 - >。我可以做什么?

What if I want to implement graph? Can I use smart pointers? In graphs there are cycles, but with weak_ptr I can't use "->". What can I do?

我在StackOverflow上阅读了一些文章,参考和主题,但看起来我还是没有得到聪明的指针。真的,为什么不存在一些weak_ptr的变体与 - >?

I read some articles, reference and topics on StackOverflow, but it looks like I still don't get smart pointers. Really, why doesn't exists some variant of weak_ptr with "->"?

推荐答案

从概念方面,实施一。智能指针代表所有权。智能指针的存在不会使原始指针作为非拥有观察者的角色失效。

Approach this from the conceptual side, not the implementation one. Smart pointers represent ownership. And existence of smart pointers does not invalidate the role of raw pointers as non-owning observers.

一个单一的,明确定义的所有者(例如图形拥有所有的顶点和边缘)?如果是这样,使用 std :: unique_ptr 来保存图形中的顶点和边,并使用顶点和边内的原始指针来引用对方。

Does each object have a single, clearly defined owner (e.g. a graph owns all of its vertices and edges)? If so, use std::unique_ptr to hold the vertices and edges in the graph, and use raw pointers inside vertices and edges to refer to each other.

共享所有权是否适用(例如,只要至少有一个边连接到顶点,顶点只存在)?如果是这样,使用 std :: shared_ptr 代表所有权,再次使用非拥有的观察者的原始指针。如果你需要相互所有权(即所有权周期),其中一个顶点只存在,只要边缘引用它,并且边缘只存在,只要顶点引用它,然后1.仔细检查这样的设计是正确和可维护,如果是这样,在循环中的某处使用 std :: weak_ptr 打破所有权循环。您可以随时通过 lock() a weak_ptr 获取 shared_ptr

Is shared ownership applicable (e.g. a vertex only exists as long as at least one edge is connected to it)? If so, use std::shared_ptr to represent that ownership, again with raw pointers for non-owning observers. If you need mutual ownership (i.e. ownership cycles) where "a vertex only exists as long as an edge refers to it, and an edge only exists as long as a vertex refers to it," then 1. double-check that such design is correct and maintainable, and 2. if so, use a std::weak_ptr somewhere in the cycle to break the ownership loop. You can always lock() a weak_ptr to obtain a shared_ptr.

对于你的特定图形场景,我相信图表拥有的一切将是最合乎逻辑的所有权方案;但这取决于你的任务的特质。

For your particular graph scenario, I believe "everything's owned by the graph" would be the most logical ownership scheme; but that depends on the idiosyncracies of your task.

这篇关于智能指针+周期+“ - >”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆