Does Const have an effect on the execution

综合编程 Hello, buddy! (源链)

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.


Janus #webrtc Video Room is getting a collection o... CoSMo and Meetecho have been working together for some time as the #webrtc A-Team. So far the contributions described in different blog posts have ma...
Build2, a Cargo-like dependency and build manager ... The build2 Toolchain Introduction Revision 0.7 , May 2018 This revision of the docume...
Part01_CMakeLists构建管理多个模块的C代码... 一、目录结构 根据我的个人管理习惯我喜欢在app目录下的CMakeLists引入到CPP目录下如果有多个项目每个项目构建一个CMakeLists分开管理。 二、app目录下的CMakeLists语法 cmake_minimum_required(VERSION 3.4...
C/C++各种类型的快速初始化 数组的初始化 普通的数组可以使用大括号来初始化,且这个大括号是可以嵌套使用的: int a = { { {0} } }; C++ 11中,std::vector 也可以使用括号来初始化, ...
.NET C#到Java没那么难,MVC篇 最典型的JAVA MVC就是JSP + servlet + javabean的模式。比较好的MVC,老牌的有Struts、Webwork。新兴的MVC 框架有Spring MVC、Tapestry、JSF等。 在这里我们对比一下 mvc和Spring mvc,至于为什么拿Sprin...
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

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

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

使用声明 | 英豪名录