Boost::[scoped/shared/weak/intrusive]_ptr Questions

Started by
0 comments, last by jpetrie 15 years, 11 months ago
I just finished reading about all the "pointer wrappers" that are provided in Boost and I had some questions: (1) I read that the libraries are "thread safe". What kind of threading guarantees are made exactly? (2) It was said that weak_ptr<>'s can used to resolve cyclic references, but I didn't see this issue clearly illustrated. Can someone illustrate this problem and how it can be resolved by use of weak_ptr<>
Advertisement
Quote:
(1) I read that the libraries are "thread safe". What kind of threading guarantees are made exactly?

The same as those of built-in types (that is to say, not much). See here.

Quote:
(2) It was said that weak_ptr<>'s can used to resolve cyclic references, but I didn't see this issue clearly illustrated. Can someone illustrate this problem and how it can be resolved by use of weak_ptr<>

Imagine two objects -- for example, two objects in a parent-child relationship. Parent has a pointer to all it's children. Each child has a pointer to its parent. A given pair of parent-child links is a cyclic reference -- the parent points to the child points to the parent points to the child...

Since shared_ptr is reference counted, the parent pointing to the child will keep the refcount of the child at (at least) one until the parent is destroyed. But the parent won't be destroyed until it's refcount is 0. And since the child points to the parent, the parents refcount will be at least one.

The only way to resolve this is to manually break the cycle, by nulling one of the links. Alternatively, a weak pointer can be used (probably to establish the child's pointer to the parent) -- a weak pointer is essentially a non-reference-incrementing 'view' of the relationship.

This topic is closed to new replies.

Advertisement