Why do we need weak_ptr in C ++ 11?

I read the book "C ++ Standard Library" by Nikolai M. Josuttis for understanding weak pointers. The author mentioned 2 reasons for having weak_ptr, and I have no second reason. Can someone give a simple explanation along with an example of the reason below (cited in the book):

Another example occurs when you explicitly want to share, but do not own the object. Thus, you have the semantics that the lifetime of a reference to an object survives the object to which it refers. Here, shared_ptrs will never release the object, and regular pointers may not notice that the object they are referencing is already invalid, which poses a risk of access to the released data.

+4
source share
3 answers

The second half of this statement should be clear: if the pointer is not a pointer to the owner, then the object that it points to can be deleted by any software that owns it, and then you will have a standard link to cheat.

So this is the problem: you have objects belonging to some piece of software that allows other software to have access to it - but other software will not share ownership. Thus, the owner can delete it at any time, and other software should know that his pointer is no longer valid.

Maybe an example will help:

, , , , . , , , , .

, , . 10 . 100 , 100 .

, . 10 .

, , - , , , . , , .

, , , , ( , ).

( , .)

+8

struct my_thing : std::enable_shared_from_this<my_thing>
{
  void start()
  {
    auto weak_self = std::weak_ptr<my_thing>(shared_from_this());
    _timer.set_callback([weak_self] {
      if (auto self = weak_self.lock()) {
        self->respond_to_timer();
      }
    });
  }

  void respond_to_timer()
  {
    // do something here
  }

  SomeTimer _timer;
};

my_thing , , my_thing. , my_thing.

weak_self weak_ptr .

+4

:.

struct node
{
   std::shared_ptr<node> left_child;
   std::shared_ptr<node> right_child;
   std::weak_ptr<node> parent;
   foo data;   
};

node left_child right_child, . - node , , , , . (, left_child right_child shared_ptr)

+2

All Articles