Smart indicators shared_ptr and weak_ptr, parent and descendant ratio



  • I understand the typical use of weak_ptr is:

    class Child {
        private :
            weak_ptr<Parent> mParent ;
    } ;
    

    class Parent: public enable_shared_from_this<Parent> {
    private :
    shared_ptr <Child> mChild ;
    };

    So the parent owns the descendants and descendants will be destroyed when the parent is destroyed.

    Are there any cases where it is more convenient to do the opposite?

    class Child {
    private :
    shared_ptr<Parent> mParent ;
    } ;

    class Parent: public enable_shared_from_this<Parent> {
    private :
    weak_ptr <Child> mChild ;
    };



  • Of course they do. Mostly when the parent is a large resource and children provide access to parts of the resource. At the same time, the parent is responsible for the release of the resource. For example, this case would be appropriate. https://msdn.microsoft.com/en-us/library/windows/desktop/aa366711(v=vs.85).aspx ♪ The parent will contain a cathedral descritor, and the subsidiary objects will be marked from this body. If we release the subject of the kit, the signs will become unqualified, so the release order must be monitored. In fact, it is logical to place this work on standard classes.

    By the way, http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr (Number 8 on reference) oriented towards such a template:

     template< class Y > 
     shared_ptr( const shared_ptr<Y>& r, T * ptr );
    

    It's supposed to be here. r - it's a parent. ptr - A child. Access will be granted to the index ptrbut when the smart indicator is removed, it will be released r♪ Here's example:

    struct Parent
    {
       int Child;
    };
    

    auto parent = std::make_shared<Parent>();
    auto child = std::shared_ptr<int>(parent, &parent->Child);

    parent->Child = 10;
    bool is_ten = *child == 10; // OK

    parent = nullptr; // Parent не удален, он продолжает жить в child
    *child = 11; // OK
    child = nullptr; // а вот теперь Parent удаляется




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2