【发布时间】:2016-03-16 08:39:02
【问题描述】:
我有一个表示运行时上下文并构建树的类,树根保存在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。你最好也阅读这个答案stackoverflow.com/a/20850223/555515 -
@neuront:不,你没有。
-
移动src后包含nullptr,reset没有意义!
-
如果您发现自己在 unique_ptr 上调用
release(),则警告您的逻辑可能不合理。 -
@RichardHodges 除非您必须将所有权传递给 C API。