【发布时间】:2014-01-13 10:51:10
【问题描述】:
我认为我的问题类似于shared_ptr and weak_ptr differences,但我有兴趣了解它们如何协同工作,而不是列出差异。
shared_ptr and weak_ptr 上的维基百科页面指出 weak_pointer 可用于解决循环依赖问题,并给出了一个示例:
std::shared_ptr<int> p1(new int(5));
std::weak_ptr<int> wp1 = p1; //p1 owns the memory.
{
std::shared_ptr<int> p2 = wp1.lock(); //Now p1 and p2 own the memory.
if(p2) //Always check to see if the memory still exists
{
//Do something with p2
}
} //p2 is destroyed. Memory is owned by p1.
p1.reset(); //Memory is deleted.
std::shared_ptr<int> p3 = wp1.lock(); //Memory is gone, so we get an empty shared_ptr.
if(p3)
{
//Will not execute this.
}
但是我没有看到循环依赖,所以我不明白weak_pointer是如何解决问题的。
我本来希望看到一些对象 a 指向一个对象 b,而 b 以某种方式指向 a(weak_ptr 在有向图边之一之间填充以破坏链)。
这个例子是好的,我的想法是坏的吗?或者有没有更好的问题和解决方案的例子?
【问题讨论】:
-
"state aweak_pointer 可以用来解决循环依赖问题" 两者都是完全错误的;弱引用用处不大,循环依赖不是一个
标签: c++ shared-ptr circular-dependency weak-ptr