修改 C++ 中的 const int

时间:2023-02-23
本文介绍了修改 C++ 中的 const int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

运行下面的代码显示&x=ptr,那么x和*ptr怎么不相等?

running the following code shows that &x=ptr, so how come x and *ptr are not equal?

const int x=10;
int* ptr =(int*) &x;
*ptr = (*ptr)+1;

cout << &x << " " << x << "  " << ptr <<"  " <<*ptr;  //output : 0012FF60 10  0012FF60  11

推荐答案

C++ 实现只需要您遵守规则才能使程序运行.你违反了规则.C++ 实现可能是这样的:

The C++ implementation is only required to make a program work if you obey the rules. You violated the rules. The C++ implementation likely behaved this way:

  • 因为 x 被声明为 const,C++ 实现知道只要你遵守规则,它的值就不会改变.因此,无论在何处使用 x,C++ 实现都会使用 10,而无需费心检查 x 是否已更改.
  • 因为 *ptr 指向一个非常量 int,所以实际执行了存储和读取操作.这些工作"是因为它指向的内存(表示 x 的地方)实际上并未被操作系统标记为只读.因此,您可以进行修改,尽管您不应该这样做.
  • Because x is declared const, the C++ implementation knows its value cannot change as long as you obey the rules. So, wherever x is used, the C++ implementation uses 10 without bothering to check whether x has changed.
  • Because *ptr points to a non-const int, stores to it and reads from it are actually performed. These "work" because the memory it points to (where x is represented) is not actually marked read-only by the operating system. Thus, you are able to make modifications in spite of the fact that you are not supposed to.

请注意,如果您遵守规则,C++ 实现的行为将可以工作.如果您没有修改 x,那么在 x 出现的任何地方使用 10 都会正常工作.或者,如果您没有将 x 声明为 const,那么 C++ 实现不会假定它总是 10,因此每当 x 被访问.这就是 C++ 标准对实现的所有要求:如果你遵守规则,它就可以工作.

Observe that the behavior of the C++ implementation would work if you obeyed the rules. If you had not modified x, then using 10 for x wherever it appeared would have worked normally. Or, if you had not declared x to be const, then the C++ implementation would not have assumed it would always be 10, so it would get the changed value whenever x was accessed. This is all the C++ standard requires of an implementation: That it work if you follow the rules.

当您不遵守规则时,C++ 实现可能会以看似不一致的方式中断.

When you do not follow the rules, a C++ implementation may break in seemingly inconsistent ways.

这篇关于修改 C++ 中的 const int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:检查一个指针是否指向堆上分配的内存 下一篇:修改 char *const 字符串

相关文章

最新文章