Does Const have an effect on the execution

The other day, a C++ trainer said to me that “const” does have meaning only in compile time (statically) and thus doesn’t have an influence in runtime… but when I test this example :

const int x = 5;
int * px = const_cast(&x);
*px = 10;
std::cout << "x = " << x <<std::endl; // x = 5 ???

x is not modified with 10 ! whereas, this example works as expected if we use pointers:

const int * x = new int(5);
int * px = const_cast(x);
*px = 10;
std::cout << "x = " << *x <<std::endl; // x = 10

So, this C++ trainer is wrong ?

It’s undefined behaviour to modify a const T
via const_cast
. This allows the compiler to optimise your code assuming it never happens. In your first code example, the compiler probably inserted a literal 5
in the code during the call to operator<<
.

Your second example is completely well defined, because x
is really pointing at an int
, not
a const int
. In this case, casting away the const
ness is fine.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Does Const have an effect on the execution

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录