简体   繁体   English

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

[英]Why can't assign const initialize while compile by pointer

I'm curious about why my research result is strange我很好奇为什么我的研究结果很奇怪

#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;
}

why the constant var initialize while runtime can completely change, but initialize while compile will only changes pointer's var?为什么常量 var initialize while runtime 可以完全改变,而 initialize while compile 只会改变指针的 var?

The function isn't really that relevant here. function 在这里并不那么重要。 In principle you could get same output (0:1) for this code:原则上,您可以为此代码获得相同的 output (0:1):

int main() {
    const int a = 0;
    int* ra = (int*)((void*)&a);
    *ra = 1;
    std::cout << a << ":" << *ra;
}

a is a const int not an int . aconst int不是int You can do all sorts of senseless c-casts, but modifiying a const object invokes undefined behavior .您可以进行各种无意义的 c-cast,但修改const object 会调用未定义的行为

By the way in the above example even for std::cout << a << ":" << a;顺便说一下,在上面的例子中,即使是std::cout << a << ":" << a; the compiler would be allowed to emit code that prints 1:0 (or 42:3.1415927 ).编译器将被允许发出打印1:0 (或42:3.1415927 )的代码。 When your code has undefinded behavior anything can happen.当您的代码具有未定义的行为时,任何事情都可能发生。

PS: the function and the different outcomes is relevant if you want to study internals of your compiler and what it does to code that is not valid c++ code. PS:如果您想研究编译器的内部结构以及它对无效 c++ 代码的代码的作用,则 function 和不同的结果是相关的。 For that you best look at the output of the compiler and how it differs in the two cases ( https://godbolt.org/ ).为此,您最好查看编译器的 output 以及它在两种情况下的不同之处( https://godbolt.org/ )。

It is undefined behavior to cast a const variable and change it's value.强制转换const变量并更改其值是未定义的行为。 If you try, anything can happen.如果你尝试,任何事情都可能发生。

Anyway, what seems to happen, is that the compiler sees const int a = 0;无论如何,似乎发生的事情是编译器看到const int a = 0; , and, depending on optimization, puts it on the stack, but replaces all usages with 0 (since a will not change.). , 并且,根据优化,将其放入堆栈,但将所有用法替换为 0(因为a不会改变。)。 For *ra = 1;对于*ra = 1; , the value stored in memory actually changes (the stack is read-write), and outputs that value. ,存储在 memory 中的值实际上会发生变化(堆栈是可读写的),并输出该值。

For const int a = test();对于const int a = test(); , dependent on optimization, the program actually calls the function test() and puts the value on the stack, where it is modified by *ra = 1 , which also changes a. ,依赖于优化,程序实际上调用了 function test()并将值放入堆栈,在那里它被*ra = 1修改,这也改变了 a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM