Search code examples
c++c++17smart-pointersunique-ptrweak-ptr

How to give a child a weak pointer to a parent? (C++)


I've read here that, in a situation where some parent object uniquely owns several children, and each child needs to be able to access its parent, a weak pointer should be used as the back-pointer instead of a shared pointer so as to avoid a dependency cycle.

I have two questions:

  1. What are the advantages of giving a weak pointer to the parent as opposed to a simple reference?
  2. In the code below, how should I pass each child a weak pointer to its parent? I know you can inherit from std::enable_shared_from_this to get a shared pointer from this. Is there an equivalent for weak pointers? Or something else?
#include <memory>
#include <vector>

class Parent;

class Child {
 public:
  void set_parent(std::weak_ptr<Parent> parent) {
    parent_ = parent;
  }
  std::weak_ptr<Parent> parent_;
};

class Parent {
  void add_child(std::unique_ptr<Child> child) {
    // child->set_parent(???);
    children_.push_back(std::move(child));
  }
  std::vector<std::unique_ptr<Child>> children_;
};

Solution

  • weak_ptrs come from shared_ptrs. If your parent nodes "uniquely own" the children, then the children cannot have weak_ptrs to their parents, as this would require that a shared_ptr to them exist somewhere.

    Note that the example you cite does not state anything about "unique ownership" of the relationship between the items.

    Furthermore, so long as the parents never relinquish ownership of the children to code outside of the system, there's no reason to not just have a regular pointer to the parent (it needs to be a pointer because a reference cannot be changed). The pointer will always be valid (from outside of the system), since a parent must exist in order for the child to exist. That's what unique ownership means, after all.