我有一个代表运行时上下文并构建树的类,树的根节点保存在unique_ptr
中。当构建树完成后,我想提取该树。代码如下(不可运行,这不是一个调试问题):
class Context {
private:
std::unique_ptr<Node> root{new Node{}};
public:
// imagine a constructor, attributes and methods to build a tree
std::unique_ptr<Node> extractTree() {
return std::move(this->root);
}
};
因此,我使用了 std::move()
来提取 Context
实例中的根节点。
然而,使用 std::move()
也有其他替代方法,例如:
std::unique_ptr<Node> extractTree() {
// This seems less intuitive to me
return std::unique_ptr<Node>{this->root.release()};
}
std::move()
是最好的选择吗?
this->root
后,您需要从中调用reset
。最好也阅读一下这个答案 https://dev59.com/RWEi5IYBdhLWcg3w6PvZ#20850223。 - neurontrelease()
,那么这是一个警告,你的逻辑很可能不稳定。 - Richard Hodges