在函数返回类型中返回右值引用与按值返回 [英] Return rvalue reference vs return by value in function return type

查看:71
本文介绍了在函数返回类型中返回右值引用与按值返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我有一个函数,它从一段数据构造一个字符串,然后返回它.此字符串未在其他任何地方使用,因此接收方对其使用移动分配或移动初始化是安全的.

In my code I have a function that constructs a string from a piece of data and then returns it. This string isn't used anywhere else, so it's safe for the receiving side to use move-assignment or move-initialization on it.

std::string ReadString(...) {
    ...
    return std::string(...)
}

这基本上就是我所拥有的.使函数返回类型 std::string&& 有什么意义,因为返回的值是右值?

This is basically what I have. Is there any point in making the function return type std::string&&, since the value being returned is an rvalue?

std::string&& ReadString(...) {
    ...
    return std::string(...)
}

我担心的是,当我们返回字符串时可能会产生多余的副本,并且可以通过将返回类型设为右值引用来缓解这种情况.

My concern is that there might be an excess copy being made when we return our string, and that it can be alleviated by making the return type an rvalue reference.

我怀疑编译器可能也能够针对这些场景进行优化,但是,我不确定.

I suspect that the compiler may also be capable of optimizing for these scenarios, however, I am not sure.

所以问题是 - 在这种情况下将返回类型设为右值引用有什么意义吗?为什么?另外,如果没有,那么返回右值引用的函数有哪些可能的应用?

So the question is - is there any point in making the return type an rvalue reference in this case and why? Also, if there isn't, then what are possible applications for functions returning rvalue references?

谢谢.

推荐答案

返回对即将被销毁的对象的引用始终是错误的:被引用的对象将被销毁,然后才能以任何形式使用.使引用成为右值引用不会改变这一点,它只会返回一个临时编译.

Returning a reference to an object being about to be destroyed is always wrong: the referenced object will be destroyed before it can be used in any form. Making the reference an rvalue reference doesn't change that, it just makes returning a temporary compile.

请注意,按值返回临时字符串可能会导致复制省略,即对象可能会直接在使用它的位置构造.如果没有发生这种情况,如果返回类型有移动构造函数(有用于 std::string),则对象将被移动.请注意,当返回函数局部变量而不是临时变量时,同样适用.

Note that returning a temporary string by value will probably result in copy elision, i.e., the object is probably going to be constructed directly in the location where it is used. If that doesn't happen the object will be moved if there is a move constructor for the return type (there is for std::string). Note that the same applies when returning a function local variable instead of the temporary.

这篇关于在函数返回类型中返回右值引用与按值返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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