const_casting question [duplicate]

落花浮王杯 提交于 2019-11-27 07:26:31

问题


This question already has an answer here:

  • Two different values at the same memory address 6 answers

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?


回答1:


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:

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:

  • The const_cast operator (IBM)
  • C++ const_cast usage instead of C-style casts
  • const_cast 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.



来源:https://stackoverflow.com/questions/4518630/const-casting-question

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