unique_ptr成员的向量

Vector of unique_ptr member

本文关键字:向量 成员 ptr unique      更新时间:2023-10-16

>我有以下内容:

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;
};

我希望类的用户有权访问子节点(读取或读取和写入)。我怎样才能做到这一点?

编辑

我试过了: 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();