【发布时间】:2019-11-24 17:30:39
【问题描述】:
在 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。 请告诉我第二种情况会发生什么,为什么?
【问题讨论】:
-
未定义的行为。
-
不要使用 C 风格的转换,你可以很容易地避免遇到这种未定义的行为。
static_cast不会编译,你必须停下来思考“为什么”? -
C++ 中有很多东西会让你更难用锤子击中自己的拇指,但如果你收紧并瞄准你的拇指......你可能会击中你的拇指。
-
如果你对编译器撒谎(
(int*)&i),编译器会做出意想不到的事情。 -
如果您想知道为什么在更改原始值后会打印原始值,答案可能是编译器将
i的任何使用替换为其值,即12。由于它是一个常量,并且不允许任何有效代码对其进行修改,因此编译器的简化是有效的行为。无论如何,如果仍然不清楚,您的代码已损坏并导致所谓的“未定义行为”(搜索该术语!)。