7

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?

4

1 に答える 1

3

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.

于 2012-05-12T11:52:30.787 に答える