Search code examples
c++move

Pass by value/reference for a parameter that will be moved within function


If you have a function parameter that is intended to be moved into a variable within the function, would you have want to use pass by reference instead of pass by value?

For example, is there ever any benefit to using

void func(T &object2move)
{
  T obj{std::move(object2move)};
}

vs.

void func(T object2move)
{
  T obj{std::move(object2move)};
}

In addition to the above, is the only case where you want to use the following code when you only want func to take in an rvalue?

void func(T object2move)
{
  T obj{object2move};
}

Is the answer to these questions dependent on what T is?


Solution

  • If your function will definitely move from the given value, then the best way to express this is by taking an rvalue-reference parameter (T&&). This way, if the user tries to pass an lvalue directly, they will get a compile error. And that forces them to invoke std::move directly on the lvalue, which visibly indicates to the reader that the value will be moved-from.

    Using an lvalue-reference is always wrong. Lvalue-references don't bind to xvalues and prvalues (ie: expressions where it's OK to move from them), so you're kind of lying with such an interface.