C++ 吗?标准规定这两种访问数组的方法是否相同或不同?
考虑以下数组和两个系列的赋值:
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++ 标准是否规定编译器应以相同或不同的方式实现这两个系列的赋值?
Considering following array and two series of assignments:
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';
Does C++ standard dictate whether these two series of assignments should be implemented identically or differently by the compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,该标准没有要求实现细节必须相同。 1.9/1:
因此,只有“可观察的行为”必须是相同的。可观察行为在 1.9/6 中定义:
用于实现此目的的确切指令不是“可观察的行为”,并且在您的示例中,由于数组不是
易失性
,因此写入的顺序也是不可观察的。事实上,除非您稍后使用该数组,否则写入本身是不可观察的。对于实现的优化器来说,在一种情况下成功删除整个代码片段而不是在另一种情况下成功删除整个代码片段是合法的,尽管可能令人惊讶的是它只能管理一个。No, the standard makes no requirements that the implementation details must be the same. 1.9/1:
So only the "observable behavior" has to be the same. Observable behavior is defined in 1.9/6:
The exact instructions used to achieve this are not "observable behavior", and in your example since the array is not
volatile
, the order of writes isn't observable either. In fact, unless you use the array later, the writes themselves aren't observable. It would be legal for the implementation's optimizer to successfully remove the entire code snippet in one case but not the other, although perhaps surprising that it could manage only one.该标准不保证任何实施,仅保证“可观察的行为”。因此,它最终可能会在每个实现的各种实现之间随机选择,包括根本不进行分配。其中每一个每次遇到时都可能以不同的方式进行编译。
这样做的目的是针对特定平台和上下文的优化。
(例如,如果编译器在 char[3] 声明之后添加一个填充字节,它可能会通过分配单个 32 位值来初始化。这些分配的顺序可能会改变,等等。)
The standard doesn't guarantee any implementation, just "observable behavior". Thus, it might end up randomly choosing between various implementations for each, including not making the assignments at all. Each of these might be compiled differently every time it is encountered.
The purpose of this is is platform- and context-specific optimizations.
(e.g. if the compiler cadds a pad byte after the char[3] declaration, it may initialize by assigning a single 32 bit value. The order of these assignment may be changed, etc.)