Quick A: It's a good style by default when you know you'll keep a copy of the parameter anyway. If you have an expensive-to-move type or otherwise want additional control, you can overload on &/&& or else perfect-forward.
Recently on SO:
Is the pass-by-value-and-then-move construct a bad idiom?
Since we have move semantincs in C++, nowadays it is usual to do
void set_a(A a) { _a = std::move(a); }The reasoning is that if
a
is an rvalue, the copy will be elided and there will be just one move.But what happens if
a
is an lvalue? It seems there will be a copy construction and then a move assignment (assumingA
has a proper move assignment operator). Move assignments can be costly if the object has too many member variables.On the other hand, if we do
void set_a(const A& a) { _a = a; }There will be just one copy assignment. Can we say this way is preferred over the pass-by-value idiom if we will pass lvalues?
Add a Comment
Comments are closed.