Strange behavior of const_cast [duplicate]

半腔热情 提交于 2019-11-27 09:38:24

Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.

One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.

Because modifying a variable declared to be const is undefined behavior, literally anything can happen.

Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.

check out the example here for more illustration:

http://en.cppreference.com/w/cpp/language/const_cast

Any attempt to modify an object that is itself declared const by means of const_cast results in undefined behavior according to the ISO C++ Standard.

When the we refer "const object", it intends to say that the memory where the object is located may be write-protected. That is, a variable or expression of const type may denote an object stored in write-protected memory and any attempt to modify the object results in undefined behavior

EDIT: Refer this site for more info

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1994/N0571.asc

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