1

Seems like maybe shared pointers could be useful across threads when both pointers are accessing same object.

But otherwise I can't think of a single time when I would need a shared pointer and a unique pointer wouldn't do the trick. Can you?

mczarnek
  • 1,305
  • 2
  • 11
  • 24
  • 2
    Additionally to the shared ownership, `shared_ptr` also has a _type-erased deleter_, which might be useful in some cases. (For instance, you cannot create a vector of `unique_ptr` objects with different deleters.) – Daniel Langr Jun 15 '20 at 05:52
  • @DanielLangr, to be clear, `unique_ptr` may also have a type-erased deleter. – Dmitry Kuzminov Jun 15 '20 at 05:56
  • @DmitryKuzminov Yes, but such type-erasure is not provided by `unique_ptr` itself. – Daniel Langr Jun 15 '20 at 06:20
  • 1
    Apart from Acorns good answer, there are some uglier use cases - prevent leaks in legacy code without putting the effort to cleanly implement ownership semantics, quickly porting code from other languages like Java. Mostly there are better alternatives, e.g. using a shared_ptr parameter 'poisons' your function declarations and should be avoided, even if the caller uses shared_ptr (with such an interface, each caller has to use it), see Guideline R.30 - http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r30-take-smart-pointers-as-parameters-only-to-explicitly-express-lifetime-semantics – Sebastian Jun 15 '20 at 14:49

1 Answers1

3

What are situations when a shared smart pointer is needed and unique can't be used?

Every time you need shared ownership.

It should not be a common occurrence, but there are some cases that stand out, like graph-like structures (including cycles), some async programming patterns, long-lived objects with no clear owner and the desire to avoid globals, etc.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • The things become even more interesting when the `weak_ptr` is used. And a non-trivial `weak_ptr` cannot exist without a `shared_ptr` constructed. – Dmitry Kuzminov Jun 15 '20 at 06:00