0

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?

24n8
  • 1,898
  • 1
  • 12
  • 25
  • 2
    `T &object2move` is would be misleading, because when passing an lvalue to a function (without `std::move`), one doesn't normally expect it to be moved from. Also it doesn't let you pass rvalues. – HolyBlackCat Apr 23 '20 at 14:00
  • @AlanBirtles I think the choice of duplicate is very poor! That target doesn't mention r-value references, which would be an ideal solution here: `void func(T&& object2move)`. If you want to keep it closed, then [this](https://stackoverflow.com/questions/5481539/what-does-t-double-ampersand-mean-in-c11) is a 'better dupe'. Personally, I think it should be re-opened. – Adrian Mole Apr 23 '20 at 14:05

1 Answers1

1

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982