如何使用weak_ptr断开shared_ptr循环引用 [英] How to break shared_ptr cyclic reference using weak_ptr
问题描述
我已读过weak_pointers可以用来中断循环引用。
I have read that weak_pointers can be used to break cyclic references.
考虑下面的循环引用示例
Consider the following example of a cyclic reference
struct A
{
boost::shared_ptr<A> shrd_ptr;
};
boost::shared_ptr<A> ptr_A(boost::make_shared<A>());
boost::shared_ptr<A> ptr_b(boost::make_shared<A>());
ptr_A->shrd_ptr = ptr_b;
ptr_b->shrd_ptr = ptr_A;
现在上面是一个循环引用的情况,我想知道如何打破
上面的循环引用使用 weak_ptr
?
Now above is a case of cyclic reference and I wanted to know how I can break
the cyclic reference above by using weak_ptr
?
更新:
根据收到的建议我想出了
Update : Based on suggestion received I came up with the following :
struct A
{
boost::weak_ptr<A> wk_ptr;
};
boost::shared_ptr<A> ptr_A (boost::make_shared<A>());
boost::shared_ptr<A> ptr_B (boost::make_shared<A>());
ptr_A->wk_ptr = ptr_B;
ptr_B->wk_ptr = ptr_A;
推荐答案
$ b < >解决方案
循环引用的典型示例是您有两个类 A
和 B
其中 A
引用 B
,引用 A
:
The classic example of cyclic references is where you have two classes A
and B
where A
has a reference to B
which has a reference to A
:
#include <memory>
#include <iostream>
struct B;
struct A {
std::shared_ptr<B> b;
~A() { std::cout << "~A()\n"; }
};
struct B {
std::shared_ptr<A> a;
~B() { std::cout << "~B()\n"; }
};
void useAnB() {
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->b = b;
b->a = a;
}
int main() {
useAnB();
std::cout << "Finished using A and B\n";
}
如果两个引用 shared_ptr
那么说 A
拥有 B
和 B
拥有 A
的所有权,这应该响铃警报。换句话说, A
保持 B
活着和 B
保持 a
If both references are shared_ptr
then that says A
has ownership of B
and B
has ownership of A
, which should ring alarm bells. In other words, A
keeps B
alive and B
keeps A
alive.
在本例中,实例 a
和 b
只用在 useAnB()
函数中,所以我们希望它们在函数结束时被销毁,因为我们可以看到当我们运行程序时,析构函数不被调用。
In this example the instances a
and b
are only used in the useAnB()
function so we would like them to be destroyed when the function ends but as we can see when we run the program the destructors are not called.
解决方案是决定谁拥有谁。让我们说 A
拥有 B
,但 B
code> A ,然后用 A
替换 B
weak_ptr
如下:
The solution is to decide who owns who. Lets say A
owns B
but B
does not own A
then we replace the reference to A
in B
with a weak_ptr
like so:
struct B {
std::weak_ptr<A> a;
~B() { std::cout << "~B()\n"; }
};
然后,如果我们运行程序,我们看到 a $ c $
Then if we run the program we see that a
and b
are destroyed as we expect.
melpon.org/wandbox/permlink/JKW9GyfhvYOtvKfV\">实验演示
Live demo
修改:在您的情况下,你建议的方法看起来完全有效。取得 A
的拥有权,而另一些拥有 A
的拥有权。
In your case, the approach you suggested looks perfectly valid. Take ownership away from A
and something else owns the A
s.
这篇关于如何使用weak_ptr断开shared_ptr循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!