Strict anti-aliasing and std :: array vs C-style array

When compiling the following code with gcc 4.7 (g ++ - mp-4.7 (GCC) 4.7.0, created using MacPorts on OS X), I get seemingly conflicting results.

The compiler does not complain when I try to rethink and dereference the std::array section as uint32_t , but this happens when using an array of type C.

Code example:

 #include <array> #include <cstdint> int main() { std::array<uint8_t, 6> stdarr; *reinterpret_cast<uint32_t*>(&stdarr[0]) = 0; // OK uint8_t arr[6]; *reinterpret_cast<uint32_t*>(&arr[0]) = 0; // ^ error: dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing] } 

Compiler command:

 $ g++ -o test -std=c++0x -Wall -Wextra -Werror main.cpp 

Why are they treated differently?

+7
source share
1 answer

When accepting the address std::array expression arr[0] equivalent to calling the function arr.operator[](0) , which returns a reference, not an arithmetic pointer expression (arr + 0) . Perhaps the compiler does not try to “see” the call to operator[] when creating anti-aliasing warnings.

+3
source

All Articles