Confusion about `const` in compound assignment

Viewed 108

The canonical implementation of operator+= passes the RHS as a const reference:

X& operator+=(const X& rhs)

However, in

x += x;

the RHS is modified. Does this invoke the UB?

3 Answers

From dcl.type.cv:

A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path.

The reference rhs is const qualified, so it cannot be used to modify the object it refers to.

However, the object being referenced, i.e. x, is non-const, and so x itself can be modified through other access paths, e.g. in the definition of operator+=.

So the behavior is well defined in this code sample.

The const means that the reference is a reference to const and a reference to const can bind to a non-const object. Binding a reference to const to a non-const object doesn't make the object itself const. It just means that you can't modify the object through the reference to const, and if the object isn't const it can be modified in another way.

In this case, the reference is a reference to const, but the object referenced is not const, so modifying the object is fine.

Let me provide another way of thinking it.

IIRC, const is only visible for debugging. It means you cannot modify a thing from this way, i.e. this name(reference). When you compile your program the compiler will drop them out after checking you done everything in right way.

Related