samedi 30 septembre 2023

using std::forward on the same argument in a loop

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 stack overflow questions but none seemed to have what I was looking for!

Aucun commentaire:

Enregistrer un commentaire