Strict aliasing and std::array vs C

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

The compiler does not complain when I try to reinterpret and dereference a section of an std::array as an uint32_t but it does when using a C-style array.

Example code:

#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 is:

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

Why are they treated differently?


When taking the address of the std::array , the expression arr[0] is equivalent to the function call arr.operator[](0) which returns a reference, rather than the pointer arithmetic expression (arr + 0) . Perhaps the compiler does not attempt to "see through" the operator[] function call when generating aliasing warnings.

链接地址: http://www.djcxy.com/p/10738.html

上一篇: 将HTTP请求转换为SOCKS5

下一篇: 严格的别名和std :: array与C