我有一个表示运行时上下文并构建树的类,树根保存在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);
}
};
Run Code Online (Sandbox Code Playgroud)
所以我曾经std::move()从Context实例中提取根节点.
然而,有使用的替代方案,std::move()例如:
std::unique_ptr<Node> extractTree() {
// This seems less intuitive to me
return std::unique_ptr<Node>{this->root.release()};
}
Run Code Online (Sandbox Code Playgroud)
是std::move()最好的选择吗?
你肯定应该使用第一个版本,因为第二个版本基本上完成了第一个版本所做的一切,代码更多,可读性更低.
从哲学上讲,第二个版本移动了唯一的指针,不多也不少.那么为什么要绕过桌子而不是使用现有的,更具可读性和更惯用的std::unique_ptr(std::unique_ptr&&)?
最后,如果您将来某处的智能指针将保留自定义删除器,则第一个版本将确保删除器也会移动,第二个版本不会移动删除器.我可以想象一个程序员使用自定义删除unique_pointer构建非自定义删除器唯一指针release.使用移动语义,程序将无法编译.
| 归档时间: |
|
| 查看次数: |
4563 次 |
| 最近记录: |