constexpr requires the compiler to evaluate the code. And, since in the context of an abstract C ++ machine, the behavior of dummy[1] is undefined, it should emit diagnostics. (This may be a warning or an error. However, for both g++ and clang++ select the error.)
However, just because dummy[1] is undefined behavior in the context of a C ++ abstract machine does not mean that something else does not define the behavior. This means that the code does not have to be rejected (if the compiler itself should not use it). This is just undefined behavior, not a mistake.
For example, compiler writers will use access to the boundaries of border arrays, and since they write the compiler, they can ensure that the behavior that occurs is desirable. A good example is array memory management, where the returned pointer is usually one word preceding the beginning of the allocated memory (since the size should also be allocated.) Therefore, when the compiler writer needs to read the size that he or she can make ((size_t const*)ptr)[-1] .
If we say that the best way to cause a compiler error in this case is to simply use static assert: static_assert(p_[0]!='a', "String does not begin with 'a'.") .
source share