vendredi 25 janvier 2019

What are the scenarios where assignment from std::forward is preferable over assignment from std::move ? why?

While learning about std::exchange on cppreference.com , I came across its "possible implementation" which is pasted below.

  template<class T, class U = T>
  T exchange(T& obj, U&& new_value)
  {
      T old_value = std::move(obj);
      obj = std::forward<U>(new_value);
      return old_value;
  }

It looked a bit odd to see obj = std::forward in an assignment statement instead instead of std::move, which I think would have the same effect.

My understanding is that std::move is equivalent to a static_cast to rvalue reference type (but more expressive) and returns an xvalue always, whereas std::forward returns the same value type it is passed.

My question is why is std:forward used in above snippet ? and is there an easy rule of thumb to decide when this is the better choice ?

Aucun commentaire:

Enregistrer un commentaire