简体   繁体   中英

Vector of unique_ptr member

I have the following:

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

I want the user of the class to have access to the childNodes (read or read and write). How can I achieve that?

EDIT

I tried: NodeList& getChildNodes();

and I get:

/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)...); }
   ^

If you are locked into the vector of unique_ptr, and want to modify them outside the class,

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

You can't return the unique_ptr because that would move it out of the vector, leaving a nullptr behind.

What you tried is correct but I'm guessing you did this:

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

Instead this should work:

NodeList& list = node.getChildNodes();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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