struct foo
{
const int A;
int B;
foo() : A(10), B(20) {}
};
void main()
{
foo f1;
const_cast<int&>(f1.A) = 4; //line 1
const foo f2;
const_cast<int&>(f2.B) = 4; //line 2
}
Do both line 1 and 2 exhibit undefined behaviour? Would the behavior be different if f1
and f2
were shared_ptr
of types listed in code above?
The behaviour both const_cast<int&>(f1.A) = 4
and const_cast<int&>(f2.B) = 4
are undefined.
If an object is originally defined as const
, and you cast away that const
-ness and attempt to modify the object, the behaviour is undefined.
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