const_cast 问题

发布于 2024-10-09 06:42:46 字数 270 浏览 0 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2024-10-16 06:42:46

常量变量还允许编译器进行某些优化,其中之一是编译器可以将值保留在寄存器中而不是重新加载它。这可以提高性能,但不适用于发生变化的变量,因为需要重新读取这些变量。有些编译器甚至通过不分配变量而简单地替换内联值来优化常量。如果将变量 a 更改为 int 而不是 const int ,它将起作用,因为可以在有关 const_cast 运算符的文档中阅读IBM:

如果你抛弃了常量
已明确表示的对象
声明为 const,并尝试
修改一下,结果未定义。

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

顺便说一句,如果您发现自己需要使用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:

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文