Konrad
Konrad

Reputation: 40947

Passing by const copy

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.

Upvotes: 6

Views: 184

Answers (5)

Rob K
Rob K

Reputation: 8926

I've recently decided to do this. I like doing it as a sort of consistency with const & and const * parameters. const correctness makes life better, so why not go all in for it? If you know you're not going to change the value, why not make it const? Making it const communicates that intention clearly.

Upvotes: 0

rene
rene

Reputation: 166

if you define the input parameter const, you can just call const functions on that object.

anyway if you try to change that object accidentally, you will get a compiler error.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

Of course there is. You can't modify nValue inside the function.

As with const-ness in general, it's not a security measure, since you can cast it away, but a design matter.

You're explicitly telling other programmers that see your code -

"I will not modify nValue inside this function

and programmers that maintain or change your code

"If you want to modify nValue, you're probably doing something wrong. You shouldn't need to do this".

Upvotes: 4

alf
alf

Reputation: 18530

Using const you also ensure that you're not incorrectly trying to alter the value of the parameter inside the function, regardless if the parameter is modifiable or not.

Upvotes: 0

James McNellis
James McNellis

Reputation: 355039

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);

Upvotes: 5

Related Questions