This is a language lawyer question, not a good practice question.
Is the following code valid or undefined behaviour? A const object ends up calling a non-const function, but it doesn't actually modify 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();
}
The behavior is well-defined :
C++ standard, section § 5.2.11/7 [const cast]
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior. —end note ]
GetA()
does not write any member of Bob
, so this program does not involve undefined behavior.
I believe it is well-defined, since the standard only ascribes undefined behaviour to modifying a const
object. C++11 quotes follow:
[expr.const.cast] 5.2.11 §7
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a
const_cast
that casts away a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]
[dcl.type.cv] 7.1.6.1 §4
Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify aconst
object during its lifetime (3.8) results in undefined behavior. ...
GetA()
does not actually modify any object, so it doesn't have undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With