Re: [問題] 修改 const int x = 100;

看板C_and_CPP作者 (小乖)時間15年前 (2010/04/29 11:01), 編輯推噓1(106)
留言7則, 1人參與, 最新討論串2/2 (看更多)
感謝 h 大: 以下是標準規格書的說法 ISO 14882:2003 says in paragraph 7.1.5.1/4: "Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior." 所以結論就是: Do not cast pointers to constants to pointers to variables. : ============================== : #include <iostream> : using namespace std; : int main() : { : const int x = 100; : int* py = const_cast<int*>(&x); : *py = 9; : cout << "(addr,value) of x ==> " << "(" << hex << &x << "," << dec << x << : ")" << endl; : cout << "(addr,value) of *py ==> " << "(" << hex << py << "," << dec << *py : << ")" << endl; : return 0; : } : =============================== : 是不是 C++ 的標準規格又多了甚麼限制嗎? 還是甚麼原因 : 請教各位 謝謝 @@") -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.216.170.154

05/16 09:34, , 1F
雖說是未明確定義行為, 但會有這樣奇怪的結果
05/16 09:34, 1F

05/16 09:35, , 2F
我猜是編譯器做最佳化 先直接把x轉成100
05/16 09:35, 2F

05/16 09:35, , 3F
寫一個const int *fn(const int *ptr){ return ptr; }
05/16 09:35, 3F

05/16 09:35, , 4F
cout << x << "\n"; // 最佳化 cout 100
05/16 09:35, 4F

05/16 09:35, , 5F
cout << *(&x) << "\n"; // 最佳化 cout 100
05/16 09:35, 5F

05/16 09:36, , 6F
cout << *fn(&x) << "\n"; // 沒辦法最佳化 cout 9
05/16 09:36, 6F

05/16 09:36, , 7F
所以說未明確定義行為 還是不要用比較好 太可怕了
05/16 09:36, 7F
文章代碼(AID): #1BsFQIQU (C_and_CPP)
文章代碼(AID): #1BsFQIQU (C_and_CPP)