Move semantic - abhijeetk/chromium-development GitHub Wiki

  • An lvalue is an expression that represents a value that has an identifiable location in memory
  • An rvalue is an expression that represents a value that may not have a location in memory
  • An lvalue reference is a reference that can bind only to lvalues (exception: if the lvalue reference is const, it can also bind to rvalues)
  • An rvalue reference is a reference that can only bind to rvalues
  • Functions can either take by lvalue reference or rvalue reference
  • The copy constructor is a function that normally takes by const lvalue reference which means that both lvalues and rvalues can bind to it. If you pass in an lvalue, the const lvalue reference will bind to it, create a copy and leave the original object untouched. If you pass in an rvalue, the const lvalue reference will bind to it, and STILL create a copy of an rvalue (which makes no sense!)
  • To solve this problem, you make a "move constructor" which is basically like a copy constructor except it takes by rvalue reference. This constructor will be called whenever an rvalue is being passed in, and in this constructor you use swap to simply steal the guts of the rvalue instead of making a separate copy of it.
  • If you know you will not be using an lvalue after, you can use std::move() to convert it to an rvalue