Is the const qualifier useful when copying to a variable initialization?

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

eg:

  • void f(const T v) instead of void f(T v) // v does not need to be changed
  • if (const int err = f()) {/*...*/} instead of if (int err = f()) {/*...*/}
  • or even void f() {const T* const v = p; /*...*/} void f() {const T* const v = p; /*...*/} instead of void f() {const T* v = p; /*...*/} void f() {const T* v = p; /*...*/}

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

+4
source share
4 answers

In such cases, const is a reminder that this variable should not be changed. So that later (perhaps much later), when you need to change this function, you do not accidentally change the variable and add another code in this function, which depends on the immutability of the variable. The compiler will only store const variables in read-only memory if the type of variables (class) has a trivial constructor.

+2
source

const in these three contexts means you cannot change a variable. But if you leave this, the compiler will still see that you are not modifying the variable. Modern compilers will check all variable assignments and indicate that there is only one initialization.

+1
source

No, it's useless. There are no real examples of const compiler optimization. It makes no sense to declare variables like const .

+1
source

A function prototype like this:

 void f(const T& arg); 

tells the caller: "I will not modify the passed argument, although you pass it by reference."

But to pass by value:

 void f(const T arg); 

changes to the passed argument are not displayed to the caller because a copy is being created, so it does not matter for the caller whether it is const or not. But it says: "After creating a copy of the argument, this copy will not change during the execution of this function," which may be useful if you want to make sure that the person who will perform this function will consider it as a constant.

But, in addition to the fact that the design of your code is easier to understand for people who will read it in the future, using the const qualifier does not make much sense here.

0
source

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


All Articles