Martin
Martin

Reputation: 9369

Is the const qualifier useful when copy-inizializing a variable?

I would like to know what are advantages and disadvantages when using the optional const qualifier when initializing non-ref/pointer variables with a copy of a value:

for example:

Is it just a matter of style? What does the C++11 standard use in its examples? Could not const be an hint for the compiler to store the variables in some special read-only memory (in some implementations)?

Upvotes: 4

Views: 205

Answers (4)

LihO
LihO

Reputation: 42133

Function prototype like this one:

void f(const T& arg);

says to the caller: "I will not change the passed argument although you pass it by reference".

But for passing by value:

void f(const T arg);

the changes to the passed argument are not visible to the caller because copy is being created, thus for the caller it makes no difference whether it's const or not. But it says: "After the copy of the argument is created, this copy will not change during the execution of this function", which might be useful when you want to make sure that the person who will implement this function will treat it as a constant.

But apart from making the design of your code to be easier to understand by the people who will read it in the future, using const qualifier doesn't make much sense here.

Upvotes: 0

Puppy
Puppy

Reputation: 147028

Nope, it's worthless. There are no real examples of compiler optimizations based on const. There's no benefit to declaring such variables as const.

Upvotes: 1

MSalters
MSalters

Reputation: 180235

const in these 3 contexts mean that you can't alter the variable. But if you left it out, the compiler would still see that you don't alter the variable. Modern compilers will check all assignments to a variable, and spot that there's just a single initialization.

Upvotes: 1

user2116939
user2116939

Reputation: 454

In such cases const is sort of a reminder to yourself that this variable is not supposed to change. So that later (probably much later), when you need to modify this function, you will not accidentally change the variable and break other code in this function that depends on the variable's immutability. Compiler will only store const variables in read-only memory if the variables type (class) has trivial constructor.

Upvotes: 2

Related Questions