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()<<'
';
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()<<'
';
p1 = changeI(p4); // 2) 2nd cyclic ref.
cout<<p1.use_count()<<'
';
// putchar('
');
cout<<endl;
}
which outputs
4
5
4
~A : 4
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?
Thanks in advance.
See Question&Answers more detail:os