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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…