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

前端 未结 3 1174
一生所求
一生所求 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条回答
  •  一个人的身影
    2021-01-01 08:14

    You are only allowed to cast away constness of an object which is known not to be const. For example, an interface may pass objects through using a const pointer or a const reference but you passed in an object which isn't const and want/need to modify it. In this case it may be right thing to cast away constness.

    On the other hand, casting away constness of an object which was const all the way can land you in deep trouble: when accessing this object, in particular when writing to it, the system may cause all kinds of strange things: the behavior is not defined (by the C++ standard) and on a particular system it may cause e.g. an access violation (because the address of the object is arranged to be in a read-only area).

    Note that despite another response I saw const objects need to get an address assigned if the address is ever taken and used in some way. In your code the const_cast(maxint) expression essentially obtains the address of your constant int which is apparently stored in a memory area which is marked to be read-only. The interesting aspect of your code snippet is that it is like to apparently work, especially when turning on optimization: the code is simple enough that the compiler can tell that the changed location isn't really used and doesn't actually attempt to change the memory location! In this case, no access violation is reported. This is what apparently is the case when the constant is declared inside the function (although the constant may also be located on the stack which typically can't be marked as read-only). Another potential outcome of your code is (independent of whether the constant is declared inside the function or not) is that is actually changed and sometimes read as 100 and in other contexts (which in some way or another involve the address) as 200.

提交回复
热议问题