Reputation: 1319
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)...); }
^
Upvotes: 1
Views: 138
Reputation: 9602
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();
Upvotes: 1
Reputation: 5871
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.
Upvotes: 3