std :: unique_ptr :: release()与std :: move() [英] std::unique_ptr::release() vs std::move()

查看:405
本文介绍了std :: unique_ptr :: release()与std :: move()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示运行时上下文并构建树的类,树根保存在 unique_ptr 中。构建完树后,我要提取树。这是它的外观(不可运行,这不是调试问题):

I have a class that represents a runtime context and builds a tree, the tree root is held in a unique_ptr. When building the tree is done I want to extract the tree. This is how it looks (not runnable, this is not a debugging question):

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 实例中提取根节点。

So I used std::move() to extract the root node from the Context instance.

不过,还有使用 std :: move()的替代方法,例如:

However there are alternatives to using std::move() e.g.:

std::unique_ptr<Node> extractTree() {
    // This seems less intuitive to me
    return std::unique_ptr<Node>{this->root.release()};
}

std :: move()最佳选择?

推荐答案

您肯定应该使用第一个版本,因为第二个版本基本上可以完成所有操作,从哲学上讲,第二个版本移动唯一的指针,没有更多的内容,不少于其他内容。

You should definitely go with the first version as the second one basically does the everything the first version does with more code and less readability.

那么为什么要绕过桌子而不是使用已经存在的,更易读和更惯用的 std :: unique_ptr(std :: unique_ptr&)

Philosophically speaking, the second version moves the unique pointer, no more, no less. so why going around the table instead of using the already existing, more readable and more idiomatic std::unique_ptr(std::unique_ptr&&) ?

最后,如果将来某个地方的智能指针将保存 custom deleter ,则第一个版本将确保删除器也移动,第二个版本不会移动删除器。我绝对可以想象一个程序员使用 release 从自定义变量unique_pointer中构建非自定义删除器唯一指针。使用移动语义,该程序将无法编译。

And lastly, if your smart pointer somewhere in the future will hold custom deleter , the first version will make sure the deleter moves as well, the second version does not moves the deleter. I can definitely imagine a programmer building non-custom deleter unique pointer out of custom-deleter unique_pointer with using release. With move semantics, the program will fail to compile.

这篇关于std :: unique_ptr :: release()与std :: move()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆