This is sort of a follow up to this question
Consider the following snippet
void f(int const &); // f "guarantees" not to change its parameter
int main()
{
int const a = 42; // a is not modifiable
f(a); // so f definitely can't modify a
// (at least not without invoking UB), that's great
int b = 42; // b is modifiable
f(b); // but f could modify b legally? huh? not so great
}
My understanding: f can only modify b, and it must use const_cast to do so. Also, this is generally a bad idea, and should not be done. Also, there are reasons for why there is a mechanism in the language to ignore const.
If my understanding is correct, then my question is, is there a way to write a function that is guaranteed to not modify its argument. i.e. is there a way to do the following
void f(int const_really &); // f *guarantees* not to change its parameter
int main()
{
int b = 42; // even if b is modifiable
f(b); // f is not allowed to modify b legally
// (or is UB if it does)
}
Edit: One reason for doing this would be to allow the compiler to do optimizations. Currently, a function that accepts an argument by const-reference is not allowed to assume that the bits of the argument will not be modified by the function. This is because the function could do a legal const_cast, or the argument type could have mutable members.
If the function could rely on the argument not being modified, then I would assume that certain kinds of optimizations could be done (similar to whole-program optimizations that prove the argument never changes).
Is that something that could be added to the language?
If not, is there some reason why this can never be done?