[英]A pointer to const int in c++
在 C++ 中,我有下一個代碼
int main() {
int i = 1;
cout<<"i = "<<i<<endl; //prints "i = 1"
int *iPtr = &i;
cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 1"
(*iPtr) = 12; //changing value through pointer
cout<<"i = "<<i<<endl; //prints "i = 12"
cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 12"
system("pause");
return 0;
}
現在相同的代碼與常量整數i
int main() {
const int i = 1;
cout<<"i = "<<i<<endl; //prints "i = 1"
int *iPtr = (int*)&i; //here I am usint a type conversion
cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 1"
(*iPtr) = 12; //changing value through pointer
cout<<"i = "<<i<<endl; //prints "i = 1"
cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 12"
system("pause");
return 0;
}
如您所見,在第二種常量整數情況下,*iPtr 和 const i 有兩個不同的值,但指針 *iPtr 顯示為常量 i。 請告訴我在第二種情況下會發生什么,為什么?
您的第二個代碼具有未定義的行為。 您不能通過指向非常量的指針更改const
數據。 您很幸運,您的代碼在嘗試修改只讀值時並沒有直接崩潰。
無論如何,您看到的結果是因為編譯器知道i
是const
並且具有在編譯時已知的值。 所以編譯器能夠優化掉cout
語句中的i
並直接使用1
。 這就是為什么您在打印i
時看到1
而在打印*iPtr
時看到12
*iPtr
。
您正在嘗試刪除變量的 const 限定符。 在 C++ 中,您應該使用const_cast
來做到這一點。
然而, const_cast
只能在某些精確的情況下使用:constness 應該只從在頂層聲明為非常量的數據的指針/引用中刪除,否則編譯器可能會優化變量並通過指針/引用修改它會導致未定義的行為。
例如,這是不合法的:
const int i = 1;
const int *iPtr = &i;
int *iSuperPtr = const_cast<int*>(iPtr);
*iSuperPtr = 2; // Invalid : i is first declared const !!
但這完全合法:
void modifyConstIntPtr(const int *iPtr) {
int *iSuperPtr = const_cast<int*>(iPtr);
*iSuperPtr = 2; // Valid : i is first declared non-const !!
}
void modifyConstIntRef(const int &iRef) {
int &iSuperRef = const_cast<int&>(iRef);
iSuperRef = 3; // Valid : i is first declared non-const !!
}
int main() {
int i = 1;
modifyConstIntPtr(&i);
std::cout << i << std::endl;
modifyConstIntRef(i);
std::cout << i << std::endl;
}
C++ 的這方面在此處詳細說明: https : //stackoverflow.com/a/357607/3412316 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.