本文介紹了同一內存地址的兩個不同值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
代碼
#include 使用命名空間標準;int main() {const int N = 22;int * pN = const_cast(&N);*pN = 33;cout<<N<<' ' <<&N <<結束;cout<<*pN<<' ' <<pN<<結束;}
輸出
<塊引用>22 0x22ff74
33 0x22ff74
為什么同一個地址有兩個不同的值?
解決方案
為什么同一個地址有兩個不同的數據?
沒有.編譯器可以優化任何對 const 的提及,就好像您在其中寫入了它的編譯時值一樣.
請注意,如果您做了一些討厭的技巧,例如寫入為常量保留的內存,編譯器也可以生成在您運行時擦除硬盤的代碼.
Code
#include <iostream>
using namespace std;
int main() {
const int N = 22;
int * pN = const_cast<int*>(&N);
*pN = 33;
cout << N << ' ' << &N << endl;
cout << *pN << ' ' << pN << endl;
}
Output
22 0x22ff74
33 0x22ff74
Why are there two different values at the same address?
解決方案
Why are there two different datas at the same address?
There aren't. The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there.
Note that the compiler is also allowed to generate code that erases your hard disk when you run it if you do nasty tricks like writing to memory reserved for consts.
這篇關于同一內存地址的兩個不同值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!