我认为我的问题与类似,但我很感兴趣的是看它们是如何一起工作的,而不是差异列表。shared_ptr,weak_ptr和循环依赖关系
维基百科上关于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 weak_pointer可以用来解决循环依赖问题_”,两者都是完全错误的;弱引用的用途很少,并且循环依赖不是一个 – curiousguy