1

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)...); }
   ^
gosom
  • 1,299
  • 3
  • 16
  • 35
  • Not the best thing to do but you can always return a reference to it. For example, you can add the following method: `const NodeList& getChildNodes() const { return childNodes; }` – crayzeewulf Jan 28 '15 at 20:41

2 Answers2

3

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.

Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30
1

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();
James Adkison
  • 9,412
  • 2
  • 29
  • 43