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;
};
我希望类的用户有权访问子节点(读取或读取和写入)。我怎样才能做到这一点?
编辑
我试过了: 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();
相关文章:
- 向量成员在管理类指针C++队列时丢失
- C++:更新类的向量成员变量
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- 具有向量成员的基类<int>
- C++ 向量::使用类对象迭代器擦除不擦除向量成员
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 修改另一个类的向量成员时出错
- 返回对私有向量成员元素的非常量引用是否是一种不好的做法
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- std::向量成员变量 EXC_BAD_ACCESS
- 如何使用其定义附近的显式长度/值构造函数初始化向量成员变量
- "Empty"数组\向量成员 C++
- 如何使用初始值设定项列表初始化 2D 向量成员
- 如何在类定义中初始化向量成员变量
- 如何初始化结构的向量成员
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- 为向量成员和更新元素指定默认值
- 保持类的向量成员与类实例连续
- C++:在类构造函数中填充向量后,向量成员被销毁
- 通过引用另一个类方法传递向量成员变量