要移动还是不从r值ref限定方法移动? [英] To move, or not to move from r-value ref-qualified method?

查看:76
本文介绍了要移动还是不从r值ref限定方法移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的C ++ 11 +代码中,应该首选哪种返回语句构造?

In the following C++11+ code which return statement construction should be preferred?

#include <utility>


struct Bar
{
};

struct Foo
{
    Bar bar;

    Bar get() &&
    {
        return std::move(bar); // 1
        return bar;            // 2
    }
};


推荐答案

好吧,因为它是具有r值ref资格的成员函数,可能即将到期。因此,假设 Bar 实际上从移动中获得了一些收益,将 bar 移出是合理的。

Well, since it's a r-value ref qualified member function, this is presumably about to expire. So it makes sense to move bar out, assuming Bar actually gains something from being moved.

由于 bar 是成员,而不是局部对象/函数参数,因此在return语句中复制省略的通常标准不应用。除非您显式 std :: move 它将始终复制。

Since bar is a member, and not a local object/function parameter, the usual criteria for copy elision in a return statement don't apply. It would always copy unless you explicitly std::move it.

所以我的答案是选择编号一个。

So my answer is to go with option number one.

这篇关于要移动还是不从r值ref限定方法移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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