此问题取决于使用的GCC版本。至少在5.4.0上,以下代码将失败:
#include <iostream>
#include <iomanip>
#include <array>
int main() {
uint8_t buf[12] = {0};
std::array<uint8_t, 12> array{0};
uint16_t data = 0x5511;
*(reinterpret_cast<uint16_t*>(&buf[1])) = data;
*(reinterpret_cast<uint16_t*>(&array[1])) = data;
std::cout << __VERSION__ << std::endl;
}
使用此错误进行cmpilation期间:
source_file.cpp: In function ‘int main()’:
source_file.cpp:27:43: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
*(reinterpret_cast<uint16_t*>(&buf[1])) = data;
我理解对别名的关注。但是,有两个问题:
std::array
而不是常规C缓冲区?