Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by const copy

Tags:

c++

Is there any benefit (or conversely, cost) to passing a parameter by const value in the function signature?

So:

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

vs

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

The only reason for doing this that I can think of would be to ensure the parameter wasn't modified as part of the function although since it has not been passed by reference there would be no wider impact outside the function.

like image 398
Konrad Avatar asked Mar 23 '12 18:03

Konrad


Video Answer


1 Answers

The top-level const here affects only the definition of the function and only prevents you from modifying the value of nValue in the function.

The top-level const does not affect the function declaration. The following two declarations are exactly the same:

void foo(size_t nValue);
void foo(const size_t nValue);
like image 188
James McNellis Avatar answered Sep 27 '22 20:09

James McNellis