Modifying const reference argument via non-const reference argument

However, in main, I pass the same variable, referenced both by a and by b. As f modifies b, it also modifies a, 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.

Leave a Comment