簡體   English   中英

向量unique_ptr成員

[英]Vector of unique_ptr member

我有以下內容:

typedef std::vector<std::unique_ptr<Node>> NodeList;
class Node
{
 public:
    Node();
    Node(NodeType _type);
    virtual ~Node();

    NodeType getNodeType() const;
    Node const* getParentNode() const;
    // I want a member function to allow acces to the
    // childNodes vector
    bool hasChildNodes() const;

    void setParent(Node* node);
    void appendChild(std::unique_ptr<Node> node);
protected:
    NodeType _nodeType;
    Node* parentNode;
    NodeList childNodes;
};

我希望該類的用戶可以訪問childNodes(讀取或讀取和寫入)。 我該如何實現?

編輯

我試過了:NodeList&getChildNodes();

我得到:

/usr/include/c++/4.8.3/bits/stl_construct.h:75: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Node; _Dp = std::default_delete<Node>]'
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
   ^

如果您被鎖定在unique_ptr的向量中,並想在類外進行修改,

NodeList& getChildNodes() {return childNodes;}
const NodeList& getChildNodes() const {return childNodes;}

您不能返回unique_ptr,因為那樣會將其移出向量,從而留下nullptr。

您嘗試的方法是正確的,但我猜您是這樣做的:

// This will not work and will try to copy the list
NodeList list = node.getChildNodes();

相反,這應該工作:

NodeList& list = node.getChildNodes();

暫無
暫無

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

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