簡體   English   中英

復制包含共享指針列表的共享指針后面的對象

[英]copy object behind shared pointer containing a list of shared pointers

我有一個shared_ptr<Tree> tree和一個shared_ptr<TreeNode> node ,其中包含作為共享指針的子項列表。

class TreeNode
{
protected:
    std::weak_ptr<TreeNode> parent;

    /**
    A list containing the children of this node
    */
    std::shared_ptr<std::vector<std::shared_ptr<TreeEdge>>> children;

   ...

只需要給Tree一個TreeNode作為其根。

Tree::Tree(const shared_ptr<TreeNode> root)
    : root(root)
{}

因此,要創建該子樹,我嘗試獲取一個TreeNode並使用它調用Tree構造函數。

shared_ptr<TreeNode> treeNode = oldTree->getASpecialNode();
shared_ptr<Tree> newTree = make_shared<Tree>(treeNode);

現在, newTree的根是treeNode 但是問題是,每個TreeNode都指向其父節點。 treeNode

weak_ptr<TreeNode> TreeNode::getParent() const
{
    return parent;
}

通過newTree中任何TreeNode的父級來計算根時,我們將獲得與newTreeNode不同的根節點,因為newTreeNode本身具有父級。

刪除該父對象不是解決方案,因為該對象是共享的,我們將在原始Tree中使用它。 因此,我看到的唯一解決方案是復制TreeNode並復制其所有成員。

我怎樣才能做到這一點?

基於SO的其他答案,我嘗試了這個:

std::shared_ptr<TreeNode> TreeNode::clone() const
{
    auto clone = new TreeNode (*this );
    clone->setParent(weak_ptr<TreeNode>());
    return shared_ptr<TreeNode>(clone);
}

但是仍然計算父級將導致原始根節點。 因此,我無法創建子樹。

我感覺對TreeTreeNode使用shared_ptr是錯誤的,但這不是我的代碼。 我只需要添加一個功能。

必須克隆整個子樹,而不僅僅是子根。 由於沒有指針被復制,因此復制初始化克隆沒有用。 此外,您應避免使用裸指針指向已分配的內存,以確保強大的異常安全性。

未經測試的示例:

std::shared_ptr<TreeNode> TreeNode::clone() const
{
    auto clone = std::make_shared<TreeNode>();
    clone->children->reserve(children->size());
    for(const auto& c : *children) {
        auto c_clone = c->clone();
        c_clone->setParent(clone);
        clone->children->push_back(c_clone);
    }
    return clone;
}

我覺得對TreeTreeNode使用shared_ptr是錯誤的

你的感覺 當然,當節點具有父指針時,不清楚如何在多個樹之間合理地共享節點。

std::shared_ptr<std::vector<std::shared_ptr<TreeEdge>>>也似乎是過多的間接std::shared_ptr<std::vector<std::shared_ptr<TreeEdge>>>

您的克隆函數應類似於:

std::shared_ptr<TreeNode> TreeNode::clone() const
{
    auto res = std::make_shared<TreeNode>();

    for (auto child : *children) {
        res->AddChild(child->clone());
    }
    return res;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM