I have a function which modifies std::string&
lvalue references in-place, returning a reference to the input parameter:
std::string& transform(std::string& input)
{
// transform the input string
...
return input;
}
I have a helper function which allows the same inline transformations to be performed on rvalue references:
std::string&& transform(std::string&& input)
{
return std::move(transform(input)); // calls the lvalue reference version
}
Notice that it returns an rvalue reference.
I have read several questions on SO relating to returning rvalue references (here and here for example), and have come to the conclusion that this is bad practice.
From what I have read, it seems the consensus is that since return values are rvalues, plus taking into account the RVO, just returning by value would be as efficient:
std::string transform(std::string&& input)
{
return transform(input); // calls the lvalue reference version
}
However, I have also read that returning function parameters prevents the RVO optimisation (for example here and here)
This leads me to believe a copy would happen from the std::string&
return value of the lvalue reference version of transform(...)
into the std::string
return value.
Is that correct?
Is it better to keep my std::string&& transform(...)
version?
&
s is pretty nasty - it mutates the object passed to it, but its disguised to look like a pure function. It's a recipe for misunderstanding. This is possibly what makes it difficult to figure out the "right" way to make an rvalue variant of it. – Irminestd::cout << foo(transform(get_str()));
? – Heikeheil