问题
For example, in the following code:
int myarray[3];
int x = myarray[1];
Is the code guaranteed to execute successfully in constant time, with x
having some integral value? Or can the compiler skip emitting code for this entirely / emit code to launch GNU Chess and still comply with the C++ standard?
This is useful in a data structure that's like an array, but can be initialized in constant time. (Sorry, don't have my copy of Aho, Hopcroft and Ullman handy so can't look up the name.)
回答1:
It's undefined behavior.
According to the standard ([dcl.init] paragraph 12),
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ... If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases
with all the following cases addressing access of unsigned narrow character type or std::byte
, which can result in an indeterminate value instead of being undefined.
回答2:
Accessing any uninitialized data is undefined behavior.
来源:https://stackoverflow.com/questions/49696810/in-c-is-accessing-an-uninitialized-array-unspecified-behavior-or-undefined-be