Forward individual members of a Forward reference
Asked Answered
A

1

4

I have a function that potentially moves a generic argument but through their members. What of these options is more correct:

  1. This seems the more natural but it is strange because the argument is potentially moved twice [a], which is odd because the object can become invalid.

    template<class T> 
    void fun(T&& t){
        myhead_ = std::forward<T>(t).head_;
        myrest_ = std::forward<T>(t).rest_;
    }
    
  2. This can't be incorrect but it may not be moving anything.

    template<class T> void fun(T&& t){
        myhead_ = std::forward<decltype(t.head_)>(t.head_);
        myrest_ = std::forward<decltype(t.rest_)>(t.rest_);
    }
    
  3. This seems correct but too much code.

    template<class T> void fun(T& t){
        myhead_ = t.head_;
        myrest_ = t.rest_;
    }
    template<class T> void fun(T&& t){
        myhead_ = std::move(t.head_);
        myrest_ = std::move(t.rest_);
    }
    

[a] This statement is incorrect as @Angew pointed out, it only looks as if it is moved twice. std::forward (like std::move) doesn't actually move anything. At most the member is moved (by the subsequent operation decltype(myhead)::operator= but that is precisely the objective.)

Armenia answered 3/5, 2018 at 8:7 Comment(0)
M
3

Your first code is perfectly fine:

template<class T> 
void fun(T&& t){
    myhead_ = std::forward<T>(t).head_;
    myrest_ = std::forward<T>(t).rest_;
}

That is because the standard guarantees that when doing a.b and a is an xvalue (such as a forwarded rvalue reference), the result of a.b is also an exvalue (i.e. can be moved from). Also note that std::forward and std::move do not do any actual moving themselves, they're just casts. So there is no risk in moving from t twice in your code.

Multiphase answered 3/5, 2018 at 8:14 Comment(2)
@Armenia The second solution would never have moved, since t.head_ is an lvalue (since t is an lvalue). You would have needed std::forward inside the decltype. However, I've since double-checked the standard and found that the whole thing is unnecessary.Multiphase
Awesome, you might be interested in this related case. https://mcmap.net/q/664711/-move-iterators-for-containers , which involve members functions instead of members by the idea is the same.Armenia

© 2022 - 2024 — McMap. All rights reserved.