The code that your teacher showed that you are a poorly formed program does not require diagnostics because it violates the requirement that the pointers actually point to what they state that they are pointing to (otherwise known as a "strict alias").
As a concrete example, the compiler can analyze your program, noting that A not written directly and that no short was written, and prove that A never changed after creation.
All this with B can be proved in accordance with the C ++ standard, since it cannot change A in a well-formed program.
A for(;;) loop or even ranking is likely to be optimized before A is statically initialized. Your teacher code under an optimizing compiler will be optimized for undefined behavior.
If you really need a way to create an array initialized with a single value, you can use this:
template<std::size_t...Is> auto index_over(std::index_sequence<Is...>) { return [](auto&&f)->decltype(auto) { return f( std::integral_constant<std::size_t, Is>{}... ); }; } template<std::size_t N> auto index_upto(std::integral_constant<std::size_t, N> ={}) { return index_over( std::make_index_sequence<N>{} ); } template<class T, std::size_t N, T value> std::array<T, N> make_filled_array() { return index_upto<N>()( [](auto...Is)->std::array<T,N>{ return {{ (void(Is),value)... }}; }); }
and now:
int main() { auto A = make_filled_array<short, 100, 3>(); std::cout << "\n"; print(A.data(),100); }
creates a populated array at compile time, unused loops.
Using godbolt , you can see that the value of the array was calculated at compile time, and the value 3 was retrieved when I access the 50th element.
This, however, is overkill (and C ++ 14 ).
Yakk Oct 06 '17 at 14:23 2017-10-06 14:23
source share