const_cast 问题
我有以下代码:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
为什么'a'的值没有更改为29?这是否意味着在 const_casting b 时并没有删除 a 的常量性?
I have the following code:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
Why doesnt the value of 'a' change to 29? Does this mean that the constness of a is not removed when const_casting b?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
常量变量还允许编译器进行某些优化,其中之一是编译器可以将值保留在寄存器中而不是重新加载它。这可以提高性能,但不适用于发生变化的变量,因为需要重新读取这些变量。有些编译器甚至通过不分配变量而简单地替换内联值来优化常量。如果将变量 a 更改为
int
而不是const int
,它将起作用,因为可以在有关const_cast
运算符的文档中阅读IBM:您可以在此处找到有关您遇到的问题及其不起作用的更多信息:
C型
强制转换
混乱
顺便说一句,如果您发现自己需要使用
const_cast
,那么您很有可能应该重新考虑您的设计。Constant variables also allows the compiler certain optimizations, one of these is that the compiler can keep the value in the registers and not reload it. This improves performance but will not work with variables that changes since these need to be reread. Some compilers even optimize constants by not allocating a variable, but simply replacing the value inline. If you change the variable a to
int
instead ofconst int
it will work, as it can be read in the documentation about theconst_cast
operator from IBM:You can find more information about the problem you are having and why it doesn't work here:
C-style
casts
confusion
On a side note it can be noted that if you find yourself in need of using the
const_cast
there is a good chance that you should reconsider your design instead.