const_casting问题 [英] const_casting question

查看:85
本文介绍了const_casting问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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?

Why doesnt the value of 'a' change to 29? Does this mean that the constness of a is not removed when const_casting b?

推荐答案

常量变量还允许编译器进行某些优化,这是不是意味着const_casting b时a的常数不会被删除?其中的一个原因是编译器可以将值保留在寄存器中,而无需重新加载。这样可以提高性能,但不适用于已更改的变量,因为需要重新读取这些变量。一些编译器甚至通过不分配变量来优化常量,而只是内联替换值。如果将变量a更改为 int 而不是 const int ,它将起作用,因为可以在文档中阅读关于IBM的 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 of const int it will work, as it can be read in the documentation about the const_cast operator from IBM:


如果放弃了已明确将
声明为const的
对象,并尝试对
进行修改,结果未定义。

If you cast away the constness of an object that has been explicitly declared as const, and attempt to modify it, the results are undefined.

您可以在此处找到有关您遇到的问题以及为何不起作用的更多信息:

You can find more information about the problem you are having and why it doesn't work here:

另外,请注意,如果您发现自己需要使用 const_cast 的机会很大,您应该重新考虑您的设计。

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.

这篇关于const_casting问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆