Does C++ standard dictate whether these two methods of accessing the array are identical or different?
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?
No, the standard makes no requirements that the implementation details must be the same. 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.
So only the "observable behavior" has to be the same. Observable behavior is defined in 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.
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.
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.)
精彩评论