3

I have been reading this book: C++ High Performance and one example I encountered regarding move assignment was:

(as member function)

auto set_title(std::string && s){
    title_ = std::move(s); 
}

however unless the s variable is coming out of an equation as an rvalue reference, we also have to call set_title(std::move(variable_name))

in order to trigger the set_title using the rvalue signature.

I did check other places like cppreference and indeed the move inside the function definition seems to be a common behavior.

I am particularly interested/confused about the std::move of the assignment in the function, since the variable is already parsed as a rvalue reference, why doing std::move again?

Thanks!

Evg
  • 25,259
  • 5
  • 41
  • 83
user3113633
  • 133
  • 1
  • 11
  • 5
    Because a named variable is always an `lvalue`. Don't mix [types with value categories](https://stackoverflow.com/questions/56716647/rvalues-lvalues-and-formal-definitions). – Evg Jan 08 '23 at 18:49
  • 2
    An id-expression naming a variable is always a lvalue expression, regardless of its type. So you need `std::move` to turn it into a rvalue expression. Surely there must be a duplicate for this here somewhere... – user17732522 Jan 08 '23 at 18:49
  • If you also have: `auto set_title(std::string const& s) { title_ = s; }` you have all bases covered. – Eljay Jan 08 '23 at 19:07
  • I like `auto set_title( std::string s ){ title_ = std::move(s); }` As a sink function. The caller can decide if they can move the parameter or need to make the copy. – Richard Critten Jan 08 '23 at 19:18

0 Answers0