shared_ptr cycles
I am not sure I understand this. I am need to before I get myself in
trouble!
"Because the implementation uses reference counting, cycles of
shared_ptr instances will not be reclaimed. For example, if main()
holds a shared_ptr to A, which directly or indirectly holds a
shared_ptr back to A, A's use count will be 2. Destruction of the
original shared_ptr will leave A dangling with a use count of 1. Use
weak_ptr to "break cycles." "
How would a shared pointer to A, directly or indirectly hold a shared
pointer back to A?
Shared pointers hold regular pointers as far as I know?
This is the only situation I can come up with, which I would more
easily describe as "If any shared pointer that already contains a raw
pointer B, is assigned to a shared pointer that already contains B,
the reference count is incremented and will not be decremented back to
zero, when those shared pointers are destroyed" I am not even sure if
that would happen, because ...isn't the reference count decremented
when a shared pointer is assigned?
int main()
{
boost::shared_ptr<MyClass> ptr1 = new MyClass();
boost::shared_ptr<MyClass> ptr2 = ptr1; // increment ref count
to 2
ptr1 = ptr2; // decrement ref count for assignment and then
increment?
// what's the ref count? Is this what they are describing as a
"cycle"?
return 0;
}
I am not sure if that is the situation or not. I can't think of any
other situation. Can someone please give examples?
I am about to implement a copy constructor and an assingment operator
for a class which contains shared pointers and I am wary that I might
be creating "cycles" if I do that.
I am also curious, if the above situation is what they are describing,
can't I prevent it by:
int main()
{
boost::shared_ptr<MyClass> ptr1 = new MyClass();
boost::shared_ptr<MyClass> ptr2 = ptr1; // increment ref count
to 2
if( ptr1.get() != ptr2.get() )
{
ptr1 = ptr2;
}
return 0;
}
and if so, why didn't they do it in the implementation of the shared
ptr?
I am sure I am missing something...
shared pointers have been working great so far, but I haven't had any
copy construction or assignment of classes that contained them yet.