However, in
main
, I pass the same variable, referenced both bya
and byb
. Asf
modifiesb
, it also modifiesa
, which it supposedly shouldn’t
When f
modifies what b
refers to, it does not modify a
. It modifies what a
refers to, but that is okay since b
is not const
. It’s only when you try to modify what a
refers to by using a
that you have issues.
Can we really say the above code is const-correct?
Yes. You do not modify a const variable.
Other than being confusing to a reader, can the above code be the source of technical problems? Such as undefined behavior, or the compiler performing wrong simplifying assumptions?
No, your code is legal and will produce the same results on all conforming compilers.
A constant reference parameter does not make the thing that it refers to const
if it was not const
to begin with. All it does it stop you from using the reference to modify the object. Another pointer or reference to that object can still mutate it, as long as it is not const
itself.