In the following code snippet, the return s
gives the warning local variable 's' will be copied despite being returned by name [-Wreturn-std-move]
. Why is this the case?
My goal with this lambda function is to take ownership of the input string and then return it after modification through RVO or move semantics. I would really like to avoid any copying.
const auto to_upper = [](std::string&& s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::toupper(c); }
);
return s;
};
Returning std::move(s)
or std::forward<std::string>(s)
will resolve the issue, but I thought this was not necessary since the compiler can elide the use of copy constructor. Also, I think I should be using std::forward
but which one is correct and why?
Aucun commentaire:
Enregistrer un commentaire