Re: [問題] 修改 const int x = 100;
感謝 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
05/16 09:35, 2F
→
05/16 09:35, , 3F
05/16 09:35, 3F
→
05/16 09:35, , 4F
05/16 09:35, 4F
→
05/16 09:35, , 5F
05/16 09:35, 5F
→
05/16 09:36, , 6F
05/16 09:36, 6F
→
05/16 09:36, , 7F
05/16 09:36, 7F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):