const cast to a global var and program crashed (C++)

前端 未结 3 1168
一生所求
一生所求 2021-01-01 07:50
int main()
{
    const int maxint=100;//The program will crash if this line is put outside the main
    int &msg=const_cast(maxint);  
    msg=20         


        
3条回答
  •  Happy的楠姐
    2021-01-01 08:18

    Modifying an object that is const (with the exception of mutable members) results in undefined behavior (from the C++03 standard):

    7.1.5.1/4 "The cv-qualifiers"

    Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

    The above undefined behavior is specifically called out in the standard's section on const_cast:

    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-qualifier68) may produce undefined behavior (7.1.5.1). ]

    So, if you have a const pointer or reference to an object that isn't actually const, you're allowed to write to that object (by casting away the constness), but not if the object really is const.

    The compiler is permitted to place const objects in read-only storage, for example. It doesn't have to though, and apparently doesn't for your test code that doesn't crash.

提交回复
热议问题