Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict 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 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?

like image 507
StackedCrooked Avatar asked May 12 '12 11:05

StackedCrooked


1 Answers

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.

like image 67
TemplateRex Avatar answered Oct 04 '22 16:10

TemplateRex