Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const_cast rules in c++

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?

like image 551
user6386155 Avatar asked Jun 05 '18 14:06

user6386155


1 Answers

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.

like image 148
Bathsheba Avatar answered Sep 29 '22 02:09

Bathsheba