3 ms·
> Obviously that doesn't imply you should do this everywhere. I'm just pointing out it's not "wrong". The article makes a point about contracts. In their code
by tsimionescu 5y ago
> Obviously that doesn't imply you should do this everywhere. I'm just pointing out it's not "wrong".
The article makes a point about contracts. In their code base, it's always wrong, since function parameters, by convention, are only allowed to be (a) non-const values, (b) const references, or (c) non-const pointers. Anything else, in their codebase indicates an error. Their point is that these three are all you need, so that getting in the habit of only using them helps maintenance, since during code review or something you know for sure that any other parameters is a mistake someone made, not an intentional choice (because of the coding standard).
> P.S. I hear optimizers can sometimes optimize const objects, though I don't have proof handy for that example, so someone else can fact-check that part.
That can happen, if a reference to your local variable is passed to a function.
For example, tried this in Godbolt [0]
void some_func(const int& x);
void some_other_func(int x);
int bar() {
int x = 123;
some_func(x);
volatile int y = x;
}
The final line directly writes 123 to y if x is const (or if calling some_other_func()), but it reads again from memory as it is. This happens because some_func could do this:
void some_func(const int& x) {
const_cast<int&>(x) = 7;
}
If x was `const int x`, this is UB, but if x is `int x`, the program MUST write 7 to y.
Note however that this optimization only happens (with clang) IF the value of x is a compile-time constant. If instead the value is only known at runtime, there is 0 difference - the value of x is still read from the stack, not kept in a register for example.
[0] https://godbolt.org/z/YKf4ndq1v https://godbolt.org/z/YKf4ndq1v