shared_ptr和循环引用 [英] shared_ptr and cyclic references
问题描述
我正在尝试使用boost::shared_ptr
的循环引用,并设计了以下示例:
I was trying with the cyclic references for boost::shared_ptr
, and devised following sample:
class A{ // Trivial class
public:
i32 i;
A(){}
A(i32 a):i(a){}
~A(){
cout<<"~A : "<<i<<endl;
}
};
shared_ptr<A> changeI(shared_ptr<A> s){
s->i++;
cout<<s.use_count()<<'\n';
return s;
}
int main() {
shared_ptr<A> p1 = make_shared<A>(3);
shared_ptr<A> p2 = p1;
shared_ptr<A> p3 = p2;
shared_ptr<A> p4 = p3;
p1 = p4; // 1) 1st cyclic ref.
cout<<p1.use_count()<<'\n';
p1 = changeI(p4); // 2) 2nd cyclic ref.
cout<<p1.use_count()<<'\n';
// putchar('\n');
cout<<endl;
}
输出
4
5
4
~A : 4
是我误解了为boost::shared_ptr
提到的循环引用吗?因为,我期望在注释1)
和2)
之后间接引用p1
的输出方式有所不同.
因此,此代码不需要boost::weak_ptr
!那么需要weak_ptr
的循环引用是什么?
Is it that I've misinterpreted the cyclic references mentioned for boost::shared_ptr
? Because, I expected different output thinking of indirect references to p1
after comments 1)
and 2)
.
So this code doesn't require boost::weak_ptr
! So what are the cyclic references where weak_ptr
s would be required?
谢谢.
推荐答案
是的,您对此有误解.在您的示例中,所有指针都指向同一对象,没有形成任何循环.
Yes, you have misinterpreted this. In your example, all the pointers are pointing to the same object, not forming any cycles.
将p4分配给p2是空操作,因为这些指针已经等于开始.
The assignment of p4 to p2 is a no-op, since those pointers were already equal to begin with.
这是一个带有真实循环引用的示例,也许可以使事情变得清晰起来:
Here's an example with real cyclic references, maybe that will clear things up:
struct A
{
std::shared_ptr<A> ptr;
};
void main()
{
std::shared_ptr<A> x=std::make_shared<A>();
std::shared_ptr<A> y=std::make_shared<A>();
x->ptr = y; // not quite a cycle yet
y->ptr = x; // now we got a cycle x keeps y alive and y keeps x alive
}
您甚至可以使其更简单:
You can even make this even simpler:
void main()
{
std::shared_ptr<A> x=std::make_shared<A>();
x->ptr = x; // never die! x keeps itself alive
}
在两个示例中,即使您离开main之后,shared_ptrs中的对象也不会被破坏.
In both examples, the objects in the shared_ptrs are never destructed, even after you leave main.
这篇关于shared_ptr和循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!