struct

时间:2018-01-12 23:26:50

标签: c++ g++ strict-aliasing

我有一个用于重新解释数据的类,但基础数据属于同一类型,但这样做似乎违反了严格的别名。我希望能够reinterpret_cast来选择如何解释数据。这是一个例子:

#include <iostream>
#include <cstdlib>

template <int M>
struct mul {
    int i[10];
    void multiply(int idx) {
        std::cout << i[idx] * M << std::endl;
    }
};
void f(mul<1> &s, mul<2> &t) { int i = s.i[0]; t.i[0]++; if (s.i[0] == i) std::abort(); }
int main() {
    mul<1> s;
    f(s, reinterpret_cast<mul<2> &>(s)); 
}

中止表明这违反了严格的别名,即使基本类型是int *。是否有理由违反严格的别名?这个样式问题是否有另一种解决方案 - 这是一个简化的案例,想象一个更复杂的函数集和使用reinterpret_cast重新解释数据。

我使用这些重新解释的类型来传递模板化函数。

命令:

g ++ - 8 -O3 -g test.cpp -o test

输出:

中止陷阱:6

g ++ - 8 --version:

g ++ - 8(Homebrew GCC HEAD-252870)8.0.0 20170916(实验性) 版权所有(C)2017 Free Software Foundation,Inc。 这是免费软件;查看复制条件的来源。没有 保证;甚至不适用于适销性或特定用途的适用性。

0 个答案:

没有答案