Search code examples
c++c++11shared-ptrsmart-pointersweak-ptr

Give container ownership of its children, but have children store a reference to their parent using smart pointers


I would like to have all the children of a Node in a tree to be owned by their parent, and have each child store a reference to its parent. That way, when a parent Node is destroyed, all of its children are automatically destroyed. I also expect that if the root Node of the tree is destroyed, the entire tree is safely deallocated.

Node.h

#include <vector>

template <typename T>
class Node :
    public std::enable_shared_from_this<Node<T>>
{

private:
    T data_;
    std::weak_ptr<Node> parent_;
    std::vector<std::shared_ptr<Node>> children_;

public:
    Node(const T& data) : data_(data) {}
    Node(const T&& data) : data_(data) {}

    // For debug-purposes only
    ~Node()
    {
        std::cout << data_ << "Destroyed" << std::endl;
    }

    T& getData() const
    {
        return data_;
    }

    void setData(const T& data)
    {
        data_ = data;
    }

    void addChild(std::shared_ptr<Node> child) const
    {
        child->parent_ = this->shared_from_this();
        children_.push_back(std::move(child));
    }

    std::weak_ptr<Node> getParent() const
    {
        return parent_;
    }

    std::vector<std::shared_ptr<Node>>& getChildren() const
    {
        return children_;
    }
};

The idea is to store a weak_ptr to the parent so that there's no cyclic dependency, and store a vector of shared_ptrs to child Nodes.

main.cpp

#include <string>
#include "Node.h"

int main(int argc, char** argv) {

    std::shared_ptr<Node<std::string>> parentNode = std::make_shared<Node<std::string>>("Parent");

    std::shared_ptr<Node<std::string>> child1 = std::make_shared<Node<std::string>>("Child1");
    std::shared_ptr<Node<std::string>> child2 = std::make_shared<Node<std::string>>("Child2");

    parentNode->addChild(child1);
    parentNode->addChild(child2);

    return 0;
}

But, I get the following errors at compile-time

void addChild(std::shared_ptr<Node> child) const
{
    child->parent_ = this->shared_from_this(); // No viable overloaded '='
    children_.push_back(std::move(child)); // No matching member function for call to 'push_back'
}

Thanks for any assistance!


Solution

  • Your addChild member function should not be const for this to work.

    fixed exmple