簡體   English   中英

為什么在通過指針編譯時不能分配 const 初始化

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

我很好奇為什么我的研究結果很奇怪

#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?

function 在這里並不那么重要。 原則上,您可以為此代碼獲得相同的 output (0:1):

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

aconst int不是int 您可以進行各種無意義的 c-cast,但修改const object 會調用未定義的行為

順便說一下,在上面的例子中,即使是std::cout << a << ":" << a; 編譯器將被允許發出打印1:0 (或42:3.1415927 )的代碼。 當您的代碼具有未定義的行為時,任何事情都可能發生。

PS:如果您想研究編譯器的內部結構以及它對無效 c++ 代碼的代碼的作用,則 function 和不同的結果是相關的。 為此,您最好查看編譯器的 output 以及它在兩種情況下的不同之處( https://godbolt.org/ )。

強制轉換const變量並更改其值是未定義的行為。 如果你嘗試,任何事情都可能發生。

無論如何,似乎發生的事情是編譯器看到const int a = 0; , 並且,根據優化,將其放入堆棧,但將所有用法替換為 0(因為a不會改變。)。 對於*ra = 1; ,存儲在 memory 中的值實際上會發生變化(堆棧是可讀寫的),並輸出該值。

對於const int a = test(); ,依賴於優化,程序實際上調用了 function test()並將值放入堆棧,在那里它被*ra = 1修改,這也改變了 a。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM