I’m trying to write a function where the logic requires me to modify the input parameter. I want it to leave the original variable unchanged, so will need to take a copy at some point.
Here is a simplified example. X is a type that is expensive to copy and I am choosing between Bar1 and Bar2:
int Foo(const X&);
int Bar1(const X& x){
// copy x to non-const local variable
auto mutable_x {x};
// call a non-const member function to change x, to make it give the desired result when passed to Foo
mutable_x.reverse();
return Foo(mutable_x);
}
int Bar2(X x){
x.reverse();
return Foo(x);
}
I feel like Bar2 is better because it will move-construct x when an rvalue is passed in, avoiding an unnecessary copy. Is this guaranteed?
The core guidelines do not seem to cover this case as far as I can tell (https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-in). Maybe this means I should just take by const-reference as normal and accept the possibility of an extra copy.
>Solution :
Bar2 is superior, not just because it avoids an extra construction. Bar1 has an extra object in scope, which could be confused for the working value.
int Bar1_BadRefactor(const X& x){
// copy x to non-const local variable
auto mutable_x {x};
// call a non-const member function to change x, to make it give the desired result when passed to Foo
mutable_x.reverse();
// some more code
return Foo(x); // whoops
}