Return rvalue reference vs return by value in function return type [duplicate]

南笙酒味 提交于 2019-12-10 21:42:37

问题


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(...)
}

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?

Thanks.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/29332516/return-rvalue-reference-vs-return-by-value-in-function-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!