删除constexpr会更改gcc上数组的值

时间:2015-08-07 13:20:39

标签: c++ c++14 constexpr compiler-bug

在尝试回答问题并创建constexpr std::array时,我写了

// Own implementation as std::array::operator[] is not constexpr :/
template <typename T, std::size_t N>
struct array
{
    constexpr T& operator[] (std::size_t index) { return data[index];}
    constexpr const T& operator[] (std::size_t index) const { return data[index];}

    constexpr std::size_t size() const { return N; }

    T data[N];
};

constexpr array<std::size_t, 1001u> make_bottle_count()
{
    array<std::size_t, 1001u> a = {{0, 1, 2, 3, 4, 1, 2, 1, 2, 3, 1}};
    for (int i = 11; i != a.size(); ++i) {
        a[i] = 1 + std::min({a[i - 1], a[i - 5], a[i - 7], a[i - 10]});
    }
    return a;
}

int main() {
    // Change constexpr to const make gcc returns expected result
    constexpr auto bottle_count = make_bottle_count(); 

    std::cout << bottle_count[17] << std::endl;   // expect 2
    std::cout << bottle_count[65] << std::endl;   // expect 7
    std::cout << bottle_count[1000] << std::endl; // expect 100
}

但是gcc会给出意想不到的结果(2 2 2)而clang会给出预期的结果。

Live demo

constexpr删除const(或替换bottle_count)可获得两者的预期结果。

我是否调用UB,或者它是编译器(gcc)错误?

1 个答案:

答案 0 :(得分:7)

这是一个gcc错误,请参阅:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67104

我会将你的测试用例添加到bug中。