简体   繁体   English

赋予其子容器的容器所有权,但让子容器使用智能指针存储对其父容器的引用

[英]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.我想让树中节点的所有子Node都归其父节点所有,并让每个子节点都存储对其父节点的引用。 That way, when a parent Node is destroyed, all of its children are automatically destroyed.这样,当一个父Node被销毁时,它的所有子节点都会自动销毁。 I also expect that if the root Node of the tree is destroyed, the entire tree is safely deallocated.我还期望如果树的根节点被破坏,整个树就会被安全地释放。

Node.h节点.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_ptr s to child Nodes.这个想法是将weak_ptr存储到父节点,以便没有循环依赖,并将shared_ptr的向量存储到子节点。

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!感谢您的帮助!

Your addChild member function should not be const for this to work.您的addChild成员 function 不应该是 const 才能正常工作。

fixed exmple固定示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM