I need to pass a non-POD type to a C ++ function. I want to change the value inside this function, but I do not want this change to be displayed outside this function.
My first option is to pass by the value that creates the copy.
void myFunction (NonSimpleObject foo) {
foo = ~foo;
}
I could also pass by reference, which is faster during the function call, but I will need to create a copy inside so as not to affect the external value;
void myFunction (NonSimpleObject &foo) {
NonSimpleObject foo_internal = ~foo;
}
To tell the caller that I will not change the external value, I would like to include the const specifier. This, of course, is implied when called by value, but I would like to be more detailed. But passing the value of const will force me to create a second copy inside to change the value, which is also somewhat opposite to what was originally used to define the constant constructor.
void myFunction (const NonSimpleObject foo) {
NonSimpleObject foo_internal = ~foo;
}
Passing a constant reference will signal to the caller that the external value is not changing, and that only one copy is required inside the function.
void myFunction (const NonSimpleObject &foo) {
NonSimpleObject foo_internal = ~foo;
}
Which one is best used for my purpose (good performance, verbose for the caller) and what will be the advantages / disadvantages?
It also comes down to the questions: is there any advantage to copying inside a function instead of copying while passing a parameter, or vice versa?