Passing a non-POD type by value, constant, reference or constant link

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?

+3
4

, . , , .

, . const, . const , .

( , , , const .)

+9

:

  • ( - , .. )
  • , : , , , , , . const , , (.. ), , (, "" ).
  • , .

, :

void myFunction (NonSimpleObject foo) {
   //modify foo here
}
+5

(void myFunction (NonSimpleObject foo)) . foo, foo_internal.

(void myFunction (const NonSimpleObject &foo)) - foo_internal.

, .

- ?

, . , , . - , const.

+1

" , , ".

. ( , friend, .)

, -, - 1. ( , ( 2. )).

This signals the user that the transferred object will not be modified (only its local copy, but this is what you want). Passing it by value to const (your decision 3.) is slightly different: you not only signal to the user that the transferred object will not be changed, but also that the local copy cannot be changed.

Passing by reference const refers to the fact that the passed object will not be changed and there will be no changing local copy.

So you have to think about what you really want.

0
source

All Articles