Constant Copy Transfer

Is there any use (or vice versa, cost) for passing a parameter by const value in the function signature?

So:

void foo( size_t nValue ) { // ... 

against

 void foo( const size_t nValue ) { // ... 

The only reason I can think of this was to ensure that the parameter was not changed as part of the function, although since it was not passed by reference, there would be no wider impact outside the function.

+4
source share
5 answers

Of course have. You cannot change nValue inside a function.

As with const -ness, this is not a security measure, since you can drop it, but it is a design issue.

You clearly tell other programmers who see your code -

"I will not modify nValue inside this function

and programmers who maintain or modify your code

"If you want to change nValue , you are probably doing something wrong. You do not need to do this."

+4
source

The upper level of const here only affects the definition of the function and only prevents you from changing the value of nValue in the function.

The upper level const does not affect the declaration of the function. The following two ads are exactly the same:

 void foo(size_t nValue); void foo(const size_t nValue); 
+4
source

Using const, you will also make sure that you are incorrectly trying to change the value of a parameter inside a function, regardless of whether the parameter is mutable or not.

0
source

if you define an input parameter const, you can simply call the const functions for this object.

In any case, if you try to accidentally change this object, you will get a compiler error.

0
source

I recently decided to do this. I like to do this as a kind of consistency with the const & and const * parameters. Paired correctness improves life, so why not go for it all? If you know that you are not going to change the value, why not make it const? Composing const, he clearly conveys this intention.

0
source

Source: https://habr.com/ru/post/1403142/


All Articles