Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 841
Samuel Moriarty Avatar asked Jan 09 '23 15:01

Samuel Moriarty


1 Answers

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.

like image 63
Dietmar Kühl Avatar answered Jan 17 '23 15:01

Dietmar Kühl