【问题标题】:Strict aliasing and std::array vs C-style array严格别名和 std::array 与 C 样式数组
【发布时间】:2012-05-20 18:16:44
【问题描述】:

当使用 gcc 4.7(g++-mp-4.7 (GCC) 4.7.0 build with MacPorts on OS X)编译以下代码时,我得到看似矛盾的结果。

当我尝试将 std::array 的一部分重新解释和取消引用为 uint32_t 时,编译器不会报错,但在使用 C 样式数组时会报错。

示例代码:

#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]
}

编译命令是:

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

为什么他们的待遇不同?

【问题讨论】:

  • 有趣的是,我在 ubuntu 12.04、64 位的 gcc 4.7 上没有收到任何错误。
  • @juanchopanza 它可​​以与-Wstrict-aliasing=2 一起使用吗?
  • 是的,确实如此。甚至没有警告。

标签: c++ arrays reinterpret-cast strict-aliasing type-punning


【解决方案1】:

在获取std::array的地址时,表达式arr[0]等效于返回引用的函数调用arr.operator[](0),而不是指针算术表达式(arr + 0)。也许编译器在生成别名警告时不会尝试“看穿”operator[] 函数调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多