gpt4 book ai didi

c++ - const 文字与 const 函数作为右值?

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:33 24 4
gpt4 key购买 nike

我对 C++ 编译器如何处理 const 变量感到很困惑

const int constfunc()
{
return 7;
}
const int u1 = constfunc();
int* pu1 = const_cast<int*>(&u1);
*pu1 = 10;
cout << u1 << endl;
cout << *pu1 <<endl;

前面代码的结果是:1010

虽然我尝试将文字值分配给 u1 变量而不是 const 函数,但我的意思是:

const int u1 = 7;

结果会改变:710

我真的有两个困惑:1-我做了一点改变但结果不同?2-据我所知,const_cast 删除了对指向非 const 变量的 const 指针的 const 限制,但在我的 sample1 中,我可以修改 const 变量“u1”的值吗?

最佳答案

int* pu1 = const_cast<int*>(&u1);

移除了 const 限制。

*pu1 = 10;

调用未定义的行为

因此

的结果
cout << u1 << endl;
cout << *pu1 <<endl;

无法通过 C++ 标准进行预测。


这是一个小例子:

enter image description here

因此,只需编写干净的代码,不要尝试使用 cast 表达式来破坏编译器错误,除非您 100% 确定自己在做什么。

关于c++ - const 文字与 const 函数作为右值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com