使用shared_ptr时如何检测循环
shared_ptr
是 Boost 库中的引用计数智能指针。
引用计数的问题是它无法处理循环。 我想知道如何用 C++ 来解决这个问题。
请不要提出诸如“不要循环”或“使用 weak_ptr
”之类的建议。
编辑
我不喜欢只使用weak_ptr
的建议,因为显然如果你知道你将创建一个循环,那么你就不会有问题。 如果您在运行时生成 shared_ptr
,您也不知道在编译时是否会出现循环。
所以请自行删除其中使用 weak_ptr
的答案,因为我特别要求不要有此类答案......
shared_ptr
is a reference counting smart pointer in the Boost library.
The problem with reference counting is that it cannot dispose of cycles. I am wondering how one would go about solving this in C++.
Please no suggestions like: "don't make cycles", or "use weak_ptr
".
Edit
I don't like suggestions that say to just use a weak_ptr
because obviously if you know you will create a cycle, then you wouldn't have a problem. You also cannot know you will have a cycle at compile time if you generate shared_ptr
s at runtime.
So please, self delete answers that use weak_ptr
in them because I specifically asked not to have those kind of answers...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
shared_ptr
表示所有权关系。 而weak_ptr
代表意识。 多个对象相互拥有意味着您会遇到架构问题,这可以通过将一个或多个自己的更改为意识到的(即weak_ptr 的)。
我不明白为什么建议
weak_ptr
被认为是无用的。shared_ptr
represents ownership relation. Whileweak_ptr
represents awareness. Having several objects owning each other means you have problems with architecture, which is solved by changing one or more own's into aware of's (that is,weak_ptr
's).I don't get why suggesting
weak_ptr
is considered useless.我理解您对被告知使用weak_ptr来破坏循环引用而感到烦恼,而当我被告知循环引用是糟糕的编程风格时,我几乎感到愤怒。
您具体询问如何发现循环引用。 事实是,在复杂的项目中,一些引用循环是间接的且难以发现。
答案是,您不应该做出虚假声明,以免容易受到循环引用的影响。 我是认真的,我正在批评一种非常流行的做法——盲目地使用shared_ptr来完成所有事情。
您应该在设计中清楚哪些指针是所有者,哪些是观察者。
对于所有者,请使用
shared_ptr
。对于观察者,请使用
weak_ptr
- 所有观察者,而不仅仅是那些您认为可能是循环一部分的观察者。如果您遵循这种做法,那么循环引用将不会导致任何问题,您无需担心它们。
当然,当您想使用这些
weak_ptr
时,您需要编写大量代码将它们转换为shared_ptr
- Boost 确实无法胜任这项工作。I understand your annoyance at being glibly told to use
weak_ptr
to break cyclic references and myself I almost feel rage when I am told that cyclic references are bad programming style.Your ask specifically how do you spot cyclic references. The truth is that in a complex project some reference cycles are indirect and difficult to spot.
The answer is that you should not make false declarations that leave you vulnerable to cyclic references. I am serious and I am criticizing a very popular practice - blindly using shared_ptr for everything.
You should be clear in your design which pointers are owners and which are observers.
For owners use
shared_ptr
.For observers use
weak_ptr
- all of them, not just those you think may be part of a cycle.If you follow this practice then the cyclic references will not cause any problems and you don't need to worry about them.
Of course you will have a lot of code to write to convert all these
weak_ptr
s toshared_ptr
s when you want to use them - Boost really isn't up to the job.检测循环相当容易:
,但是这并不是很有用。 而且通常不可能解决引用计数指针的循环问题 - 这就是为什么发明了替代垃圾收集方案(例如生成清除)的原因。
It's fairly easy to detect cycles:
It's not, however, very useful. And it is not generally possible to solve the cycvle problem for ref-counted pointers - that's why alternative garbage colection schemes like generation scavenging were invented.
我还没有找到比绘制大型 UML 图并寻找循环更好的方法。
为了进行调试,我使用一个进入注册表的实例计数器,如下所示:
我只需将其添加到相关类中,然后查看注册表。
(ID,如果给定为“XYZ!”,将被转换为字符串。不幸的是,您不能指定字符串常量作为模板参数)
I haven't found a much better method than drawing large UML graphs and looking out for cycles.
To debug, I use an instance counter going to the registry, like this:
I just ned to add that to the classes in question, and have a look at the registry.
(The ID, if given as e.g. 'XYZ!' will be converted to a string. Unfortunately, you can't specify a string constant as template parameter)
也许是
boost::weak_ptr
和boost::shared_ptr
的组合? 这个文章可能感兴趣。A combination of
boost::weak_ptr
andboost::shared_ptr
maybe? This article may be of interest.请参阅这篇关于检测周期的文章图形。
See this post on detecting cycles in a graph.
找到循环的通用解决方案可以在这里找到:
测试链表是否有循环的最佳算法
这假设您知道列表中对象的结构,并且可以跟踪每个对象中包含的所有指针。
The generic solution to finding a cycle can be found here:
Best algorithm to test if a linked list has a cycle
This assumes that you know the structure of the objects in the list, and can follow all of the pointers contained in each object.
您可能需要垃圾收集器技术,例如 标记和清除。 该算法的思想是:
由于您正在使用
shared_ptr
,因此您无法到达的任何仍然存在的指针都应被视为循环的成员。实现
下面我描述了一个非常简单的示例,说明如何实现算法的
sweep()
部分,但它将reset()
收集器上的所有剩余指针。此代码存储
shared_ptr
指针。Collector
类负责跟踪所有指针并在执行sweep()
时删除它们。然后你可以像这样使用它:
我用 Valgrind 测试了它,没有列出内存泄漏或“仍然可达”块,所以它可能按预期工作。
关于此实现的一些注意事项:
shared_ptr
(其工作原理类似于引用计数 GC)来实现这样的垃圾收集器,因为标记和清除算法已经完成了这项工作。最后,如果您关心(2),这种实现并非闻所未闻。 CPython(Python 的主要实现)确实混合使用了引用计数和标记和扫描,但主要用于 历史原因。
实现
mark()
函数:要实现
mark()
函数,您需要进行一些修改:需要添加一个
bool 标记;< /code> 属性赋给
Cycle_t
,并用它来检查指针是否被标记。您需要编写如下所示的
Collector::mark()
函数:然后您应该修改
sweep()
函数以删除标记(如果指针)被标记,否则reset()
指针:这是一个冗长的解释,但我希望它对某人有所帮助。
You are probably in need of a Garbage Collector technique such as Mark and Sweep. The idea of this algorithm is:
Since you are using
shared_ptr
any still existing pointers you fail to reach should be considered as members of a cycle.Implementation
Below I describe a very naive example of how to implement the
sweep()
part of the algorithm, but it willreset()
all remaining pointers on the collector.This code stores
shared_ptr<Cycle_t>
pointers. The classCollector
is responsible for keeping track of all the pointers and deleting them whensweep()
is executed.You can then use it like this:
I tested it with Valgrind and no memory leaks or "still reachable" blocks were listed, so it is probably working as expected.
Some notes on this implementation:
shared_ptr
(that works like a Reference Counting GC) to implement such a Garbage Collector since the Mark and Sweep algorithm would already take care of the job.Finally, if you are concerned with (2), this kind of implementation is not unheard of. CPython (the main implementation of Python) does use a mixture of Reference Counting and Mark and Sweep, but mostly for historical reasons.
Implementing the
mark()
function:To implement the
mark()
function you will need to make some modifications:It would be required to add a
bool marked;
attribute toCycle_t
, and use it to check whether the pointer is marked or not.You will need to write the
Collector::mark()
function that would look like this:And then you should modify the
sweep()
function to remove the mark if the pointer is marked or elsereset()
the pointer:It was a lengthy explanation, but I hope it helps someone.
如果你有带有共享指针的 Cycles,你将会遇到内存泄漏。 因此,如果转储内存泄漏对象,您可以查看这些对象的类型以找到实际的循环。
If you have Cycles with shared pointers, you will have memory leak. So, if you dump memory leak objects, you can look at the types of these to find the actual cycle.
我认为您确实需要 类似 Java 垃圾收集的东西。 这个问题讨论了<的“自动循环断路器”代码>shared_ptr。
您可以在程序中使用
shared_ptr
循环并释放每个对象,但这违反了流行的建议。 流行的建议是打破shared_ptr
循环在参与循环的对象之一中使用weak_ptr
。如果您坚持在程序中保留
shared_ptr
循环,您仍然可以这样做,但您必须在销毁时手动打破shared_ptr
循环时间。这很像记住在对象上手动调用
delete
,因此您可以明白为什么不建议这样做。I think you're really asking for something like Java's garbage collection. This question talks about an "automatic cycle breaker" for
shared_ptr
.You can have
shared_ptr
cycles in your program and have every object deallocate, but it's against the popular recommendation. The popular recommendation is to break theshared_ptr
cycle by usingweak_ptr
in one of the objects that participates in the cycle.If you insist on keeping a
shared_ptr
cycle in your program, you still can do it, but you have to manually break theshared_ptr
cycle at destruction time.This is a lot like remembering to manually call
delete
on an object, so you can see why it's not recommended.回答老问题,您可以尝试侵入式指针,这可能有助于计算资源被引用的次数。
这是返回的结果。
Answer for the old question, you may try out the intrusive pointer which may help out to count how many times the resource being referred.
Here's the result returned.
只使用 Valgrind 或 LLVM 的地址清理程序怎么样?
对于类似的内容:
我看到:
definitely loss: 16 bytes in 1 block
检测到它。 您可以使用地址清理程序获得类似的输出。 我同意 Valgrind / ASan 也会检测其他内容,并且不会查明原因,但它会检测循环依赖。How about just using Valgrind or LLVM's address santizer?
For something like:
I see:
The
definitely lost: 16 bytes in 1 blocks
detects it. You can get a similar output with the address sanitizer. I agree that Valgrind / ASan will detect other stuff too and will not pin-point the cause, but it will detect the circular dependency.我知道你说“没有weak_ptr”,但为什么不呢? 让 head 带有一个weak_ptr 到tail,而tail 带有一个weak_ptr 到head 将阻止循环。
I know you said "no weak_ptr" but why not? Having your head with a weak_ptr to tail, and tail with a weak_ptr to head will prevent the cycle.