Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

When is std::weak_ptr useful?

I started studying smart pointers of C++11 and I don't see any useful use of std::weak_ptr. Can someone tell me when std::weak_ptr is useful/necessary?

Answer*

Draft saved
Draft discarded
Cancel
4
  • How can a weak reference deal with a circular dependency? Commented Jun 11, 2016 at 0:45
  • 1
    @curiousguy, a child employs a weak reference to the parent, then the parent can be deallocated when there are no shared (strong) references pointing to it. Thus when accessing the parent via the child, the weak reference has to tested to see if the parent is still available. Alternatively to avoid that extra condition, a circular reference tracing mechanism (either mark-sweep or probing on refcount decrements, both of which have bad asymptotic performance) can break the circular shared references when the only shared references to the parent and child are from each other. Commented Jan 13, 2018 at 20:14
  • @ShelbyMooreIII "has to tested to see if the parent is still available" yes, and you have to be able to react correctly to the unavailable case! Which doesn't occur with a real (i.e. strong) ref. Which means weak ref is not a drop in replacement: it requires a change in the logic. Commented Jan 17, 2018 at 23:20
  • 2
    @curiousguy you didn’t ask "How can a weak_ptr deal with a circular dependency with no change in program logic as a drop-in replacement for shared_ptr?" :-) Commented Jan 20, 2018 at 6:02

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /