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:
- What are the advantages of giving a weak pointer to the parent as opposed to a simple reference?
- 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 fromthis
. 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_;
};