Can we use `const_cast` to modify a constant variable? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 06:53:33

问题


int main()
{
    const int ia = 10;

    int *pia = const_cast<int*>(&ia);
    *pia = 5;

    std::cout << &ia << "\t" <<  pia <<endl;
    std::cout <<  ia << "\t" << *pia <<endl;

    return 0;
}

The output is:

0x28fef4       0x28fef4
10             5

*pia and ia have the same address, but they have different values. My purpose is to use const_cast to modify a constant value, but as the result shows that it does not work.

Does anyone know why?


回答1:


The reason why you see 10 printed for ia is most likely the compiler optimization: it sees a const object, decides that it's not going to change, and replaces the last printout with this:

cout<< 10 <<"  "<<*ppa<<endl;

In other words, the generated code has the value of the const "baked into" the binary.

Casting away the const-ness of an object that has originally been declared as const and writing to that object is undefined behavior:

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

Depending on the platform, const objects may be placed in a protected region of memory, to which you cannot write. Working around the const-ness in the type system may help your program compile, but you may see random results or even crashes.




回答2:


It is undefined behaviour to modify a constant value. Don't do it. If you need to modify the value, don't declare it as const.



来源:https://stackoverflow.com/questions/19208560/can-we-use-const-cast-to-modify-a-constant-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!