gpt4 book ai didi

c++ - 为什么在通过指针编译时不能分配 const 初始化

转载 作者:行者123 更新时间:2023-12-01 13:40:39 24 4
gpt4 key购买 nike

我很好奇为什么我的研究结果很奇怪

#include <iostream>

int test()
{
return 0;
}

int main()
{
/*include either the next line or the one after*/
const int a = test(); //the result is 1:1
const int a = 0; //the result is 0:1

int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra << std::endl;
return 0;
}
为什么常量 var initialize while runtime 可以完全改变,而 initialize while compile 只会改变指针的 var?

最佳答案

该功能在这里并不是那么重要。原则上,您可以为此代码获得相同的输出 (0:1):

int main() {
const int a = 0;
int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra;
}
aconst int不是 int .你可以做各种毫无意义的 c-casts,但是修改一个 const对象调用 undefined behavior .
顺便说一下,在上面的例子中,即使是 std::cout << a << ":" << a;编译器将被允许发出打印 1:0 的代码(或 42:3.1415927)。当您的代码具有未定义的行为时,任何事情都可能发生。
PS:如果您想研究编译器的内部结构以及它对无效 C++ 代码的代码的作用,则该函数和不同的结果是相关的。为此,您最好查看编译器的输出以及它在两种情况下的区别( https://godbolt.org/ )。

关于c++ - 为什么在通过指针编译时不能分配 const 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62569003/

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