c++ - C++ 标准是否规定这两种访问数组的方法是相同的还是不同的?

标签 c++ arrays reference standards

考虑以下数组和两个系列的分配:

char charArray[3];

charArray[0]='a';
charArray[1]='b';
charArray[2]='c';

char & charRef1=charArray[0];
charRef1='a';
char & charRef2=charArray[1];
charRef2='b';
char & charRef3=charArray[2];
charRef3='c';

C++ 标准是否规定了这两个系列的赋值应该由编译器以相同还是不同的方式实现?

最佳答案

不,标准没有要求实现细节必须相同。 1.9/1:

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.

所以只有“可观察的行为”必须相同。可观察行为在 1.9/6 中定义:

The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.

用于实现此目的的确切指令不是“可观察的行为”,并且在您的示例中,由于数组不是 volatile,因此写入顺序也不可观察。事实上,除非您稍后使用数组,否则写入本身是不可观察的。实现的优化器在一种情况下成功删除整个代码片段而不是另一种情况是合法的,尽管它只能管理一个可能令人惊讶。

关于c++ - C++ 标准是否规定这两种访问数组的方法是相同的还是不同的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4288348/

相关文章:

Java数组索引越界?

c - 为什么在检查 'exit' 字符串时我的代码没有在循环内终止?

c# - Azure 发布会错过引用项目引用的程序集

c++ - "virtual memory exhausted"构建 Docker 镜像时

c++ - 模板基类可以存储指向派生而不是对象的指针——为什么?

javascript - 对数组进行分组并获取每个组的最后一个和第一个数组

c++ - 我可以通过引用调用placement-new和析构函数吗?

c# - 将字节引用从 c# 传递到非托管 cpp COM dll

c++ - 如何让 List Control 中的单元格有边框?

c++ - OpenCV : convert the pointer in memory to image