This is more of a general question:
Is there any point in making a function parameter const
if it is being passed by value?
In a code I am studying, I see a lot of the following:
void some_function(const std::vector<double> some_vec);
std::vector
is passed by value, so what then is the point of the const
?
Like I would understand if the function was instead passing the vector by reference as such:
void some_function(const std::vector<double> &some_vec);
but I see no point in the const
in the former.
The point is that you prevent the function body from altering the value. The function argument is just an automatic variable within the function body and you may want to ensure it remains at its input value. Consider
int foo(int x)
{
/* lots of code */
some_other_func(x); // may modify x
/* even more code */
return x+42; // x may have been modified
}
and
int foo(const int x)
{
/* lots of code */
some_other_func(x); // will not compile if x is taken by non-const reference
/* even more code */
return x+42; // x is guaranteed at its input value
}
As a rule of thumb, declare everything const
that is not meant to be altered. Then, if you or somebody accidentally attempts to alter such a variable, a compile-time error will result.
Note also that the const
declarator has no effect in a function declaration, but only in the function definition, i.e. the following is perfectly fine (in fact recommended):
struct bar
{
int foo(int) const;
/* more code */
};
int bar::foo(const int x) const // possibly in another compilation unit
{
...
}