c++ – Shared_ptr and weak_ptr smart pointers, parent-child relationship

Question:

As far as 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 ;
};

Those. the parent owns the child and the child will be destroyed when the parent is destroyed.

Are there cases when 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 ;
};

Answer:

Of course there are. Basically when the parent is a large resource and the children are accessing parts of that resource. In this case, the parent is responsible for freeing the resource. For example, a heap from WinApi is suitable for this case. The parent will hold a handle to the heap, and the child objects will hold pointers to blocks of memory allocated from that heap. If we free the heap object, then the pointers will become invalid, so we need to keep track of the order of the release. Actually, it is logical to assign this work to standard classes.

By the way, std :: shared_ptr has a constructor (number 8 on the link) oriented to a similar pattern:

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

This assumes r is the parent and ptr is the child. This will grant access to the ptr , but when the smart pointer is deleted, r will be freed. Here's an example scenario:

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 удаляется
Scroll to Top