Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it better to pass by value in the following case?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading