0

Can anyone provide some cases in which it would be beneficial to use std::weak_ptr over std::shared_ptr? I understand the difference between them in terms of their function (std::shared_ptr keeps a reference counter and std::weak_ptr does not), and I understand the workings of smart pointers in general, I would just like to know when std::weak_ptr is preferred over std::shared_ptr, preferably with some accompanying code.

  • 1
    If you have a parent object that has a child object, the parent could have a shared_ptr to the child object, and the child object could have a weak_ptr to its parent object. (If they were both shared_ptr, they'd keep each other alive.) – Eljay Feb 05 '21 at 01:58
  • https://stackoverflow.com/questions/12030650/when-is-stdweak-ptr-useful – Retired Ninja Feb 05 '21 at 02:00
  • The cppreference web resource usually has explanation **and** example code. If you just asking to start a discussion, SO has a special flag for such questions: `opinion based`. – user14063792468 Feb 05 '21 at 02:08

0 Answers0