将const int转换为指针? [英] Casting a const int to a pointer?

查看:266
本文介绍了将const int转换为指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

通过非const指针修改const

Possible Duplicate:
Modifying a const through a non-const pointer

我有以下代码:

const int x = 5;
int *p = (int*)&x;

*p = 2; // Line 1

cout << x << " - " << *p << endl;
cout << &x << " - " << p << endl;

得到结果:

5 - 2
0012FF28 - 0012FF28

代码是奇怪的,永远不应该做。但我想知道为什么同样的地址,但有不同的结果? 行1 存储数字2?

I know the code is weird and should never do it. But I wondered why the same address but got different result? And where the Line 1 store the number 2?

推荐答案

无论如何,固有的 const 变量的值是未定义行为 [Ref#1]

Because changing the value of an inherently const variable in anyway is Undefined Behavior[Ref #1].

一旦你这样做:

*p = 2; // Line 1

所有投注均已关闭,且您的代码不再是有效的C ++代码一旦该行被写入,不能期望任何特定的行为。推测为什么未定义的行为给出任何特定的行为是无意义的,因为它允许显示任何行为 [Ref#2] / em>。

All bets are off, and your code is no longer a valid C++ code, You cannot expect any particular behavior once that line was written. To speculate why an Undefined Behavior gives any particular behavior is pointless because it is allowed to show any behavior[Ref #2] that is the meaning of Undefined Behavior.

[Ref#1]

C ++ 03标准7.1.5.1 cv限定符:

第4段:


除了可以修改任何声明为mutable(7.1.1)的类成员之外,任何尝试在一个const对象的生命周期(3.8)内修改一个const对象会导致不确定的行为。

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.

[Ref#2]

C ++ 03 Standard 1.3.24:


允许的未定义行为的范围包括完全忽略具有不可预测结果的情况,在以文件化方式表示环境特征的翻译或程序执行期间行为(有或没有发出诊断消息),以终止翻译或执行(发出诊断消息)。

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

这篇关于将const int转换为指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆