Question

Say I have an object that contains a shared_ptr to a child object.

I want the child object to have a weak_ptr to the parent object, what should the child object's constructor look like and how should I construct a child from the parent?

Thanks in advance

Was it helpful?

Solution

As you have unique owner ship of child objects the child is guaranteed not to outlive it's parent. You could have a model something like this.

struct Parent;

struct Child {
        Child( Parent& p ) : p_(&p) {}
        Parent* p_;
};

#include <memory>

struct Parent {
        std::unique_ptr<Child> c_;
        void AddChild() {
                c_.reset(new Child(*this));
        }
};

Of course, the child should be careful with anything that it does with the parent in the destructor, it might be being destroyed because its parent is going out of scope. This is about the only advantage of a child having a weak_ptr to its parent (it still won't be able to do anything with the parent from its destructor but at least it can safely tell that) but this relies on its parent being owned by a shared_ptr which is a much more inflexible design for the child.

This would be the weak_ptr solution:

// NOT RECOMMENDED
#include <memory>

struct Parent;

struct Child {
        Child( const std::shared_ptr<Parent>& p ) : p_(p) {}
        std::weak_ptr<Parent> p_;
};

struct Parent : std::enable_shared_from_this<Parent> {
        std::unique_ptr<Child> c_;
        void AddChild() {
                // Warning, undefined behaviour if this Parent
                // isn't owner by shared_ptr
                c_.reset(new Child(shared_from_this()));
        }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top