Is the following const_cast undefined behavior used?

This is a question of a language lawyer, not a question of good practice.

Is the following code valid or undefined behavior? The const object ends with a non-const function call, but does not actually change the state of the object.

struct Bob { Bob() : a(0) {} int& GetA() { return a; } const int& GetA() const { return const_cast<Bob&>(*this).GetA(); } int a; }; int main() { const Bob b; int a = b.GetA(); } 
+7
c ++ language-lawyer
source share
2 answers

The behavior is clearly defined:

C ++ Standard, Section ยง 5.2.11 / 7 [const cast]

[Note. Depending on the type of object, a write operation through a pointer, lvalue, or a pointer to a data member obtained from const_cast, which discards the -qualifier constant, may cause undefined behavior. -end note]

GetA() does not write any Bob members, so this program does not include undefined behavior.

+8
source share

I believe it is well defined, since the standard only attributes undefined behavior to modify the const object. C ++ 11:

[expr.const.cast] 5.2.11 ยง7

[Note: depending on the type of object, a write operation through a pointer, lvalue, or a pointer to a data element obtained as a result of a const_cast , which discards the qualifier qualifier, can cause undefined behavior (7.1.6.1). -end note]

[dcl.type.cv] 7.1.6.1 ยง4

Except that any member of the class declared mutable (7.1.1) can be modified, any attempt to change a const object during its lifetime (3.8) leads to undefined behavior ....

GetA() does not actually modify any object, so it does not have undefined behavior.

+4
source share

All Articles