In the absolute majority of cases, no. Const-correctness just makes it easier for humans reason about code (e.g. “ok, this part can’t be the one changing the value”).
However, there can be situations where the compiler can’t figure out if a value will be changed in a particular code path, and ao can’t apply optimizations that rely on the value staying the same.
The answer depends on the compiler. In my experience, no, it doesn't make a difference, but using some of the new C++ features such as constexpr can make a difference. The advantage of "const" is that it helps the programmer to manage object ownership, write permissions, etc. This makes the code easier to understand and reduces the chances of mistakes. Sometimes "const" is required when using libraries/APIs that enforce cons correctness.
Yes, it can affect both code generation and performance.
C++ allows overloading between const and non-const methods: class MyClass { ... void MyMethod(); void MyMethod() const; };
The compiler will select the appropriate overload based on the const-qualifier of the object (if both method-variants are present).
There are also more obscure cases, from my experience.
If you declare a global static-const variable, most compilers will place it into read-only memory, and trying to modify this variable (with a const_cast or indirect addressing) will cause an access-violation. It also allows the compiler to inline the variable in the whole translation-unit, because it knows the value cannot be modified.
That second example is quite vague of course, but it shows that the compiler cares about const-qualification in unexpected ways.
8
u/314kabinet Aug 14 '22
Congrats! But for god’s sake, use const.