Passing non-POD type by value, const value, reference or const reference
c++, constants, pass-by-reference, pass-by-value
Solution
If you need a local object, then passing by value is best. This enables move semantics, if the argument is a temporary or explicitly moved, so that unnecessary copying can be avoided.
Passing by reference forces a copy whether it's needed or not. If the reference isn't `const`, then the argument can't be a temporary. Accepting a `const` object by value and then copying it is just weird.
(Note that, in your specific examples, you don't need a local copy, just the result of applying an operator to the argument; so a `const` reference might be more appropriate.)
Problem
I need to pass a non-POD type to a C++ function. I want to modify the value inside that function, but I don't want that change to be visible outside of that function. My first option is to pass by value, which creates a copy. ``` void myFunction (NonSimpleObject foo) { foo = ~foo; } ``` I could also pass by reference, which is faster during function calling, but I would need to create a copy inside to not influence the outside value; ``` void myFunction (NonSimpleObject &foo) { NonSimpleObject foo_internal = ~foo; } ``` To signal to the caller that I will not modify the outside value, I would like to include a const qualifier. This is of course implicit when calling by value, but I would like to be more verbose. But passing a const value will force me to create a second copy inside to modify the value, which also is somewhat the opposite of what the const qualifier is used for originally. ``` void myFunction (const NonSimpleObject foo) { NonSimpleObject foo_internal = ~foo; } ``` Passing a const reference will both signal to the caller that the outside value is not changed as well as only requiring one copy inside the function. ``` void myFunction (const NonSimpleObject &foo) { NonSimpleObject foo_internal = ~foo; } ``` Which one is the best to use for my purpose (good performance, verbose to the caller) and what would be the advantages/disadvantages? This also boils down to the questions: Is there any advantage to copying inside a function instead of copying during parameter passing or vice versa?