I know there are cases where using std::forward on the same argument in a loop is wrong because it may cause moving from a moved object, like so:
template <typename T>
auto applyTenTimes(T&& arg, auto&& f){
for(int i = 0; i < 10; ++i)
f(std::forward<T>(arg));
return arg;
}
But, what about the case where the forwarded object gets assigned again? Like in this example:
template <typename T>
auto applyTenTimes(T&& arg, auto&& f){
for(int i = 0; i < 10; ++i)
arg = f(std::forward<T>(arg));
return arg;
}
Would this be valid? If yes, then why? Is it basically never creating a new object (when called with an rvalue) and just moving the arg into the function f and then gets moved back again into arg by RVO?
I tried looking at different StackOverflow questions, but none seemed to have what I was looking for!
std::forward, this will expand according to the input being an rvalue, or lvalue as follows.
both functions are perfectly valid c++ code, and both involve calling the copy/move assignment operator, as function parameters can't be copy-elided.