1

I have a class Bar which implements a move constructor.

For an instance Bar b, if I call void fooRvalRef(Bar&&) using fooRvalRef(std::move(b)) then the move constructor of Bar is not called.

On the other hand for the function void foo(Bar), calling it using foo(std::move(b)) calls the move constructor of Bar.

Why is that?

user695652
  • 3,725
  • 3
  • 32
  • 52

1 Answers1

3

std::move tries to turn the argument into an rvalue reference, that's all it does, it doesn't move the object. Since it succeeds in your fooRvalRef call, there is no need for a move constructor, it simply passes the rvalue reference to the rvalue-reference parameter.

In the case of foo(Bar) you're passing by value so, ordinarily, the copy constructor would be called. However in this case you have a move constructor and you are passing an rvalue reference, thanks to std::move, so the move constructor is called.

kfsone
  • 21,566
  • 2
  • 35
  • 66