Constants and immutability
Con.1
By default, make objects immutable
Reason
Immutable objects are easier to reason about, so make objects non-const only when there is a need to change their value. Prevents accidental or hard-to-notice change of value.
Example
for (const int i : c) cout << i << '\n'; // just reading: const
for (int i : c) cout << i << '\n'; // BAD: just reading
Exceptions
A local variable that is returned by value and is cheaper to move than copy should not be declared const because it can force an unnecessary copy.
std::vector<int> f(int i)
{
std::vector<int> v{ i, i, i }; // const not needed
return v;
}
Function parameters passed by value are rarely mutated, but also rarely declared const. To avoid confusion and lots of false positives, don't enforce this rule for function parameters.
void g(const int i) { ... } // pedantic
Note that a function parameter is a local variable so changes to it are local.
Enforcement
and returned local variables)
- Flag non-
constvariables that are not modified (except for parameters to avoid many false positives