这段代码如何产生无符号整数溢出

时间:2016-07-26 15:50:58

标签: c++ c++11

我有以下递归constexpr函数

template<size_t N, size_t O,size_t All>
constexpr int get_indices(const std::array<size_t,N> &products,
                          const std::array<size_t,N>& idx,
                          const std::array<std::array<int,O>,All> &as_all,
                          int i,
                          int it) {

    return it==0 ? as_all[i][idx[static_cast<int>(N)-1]] :
        products[it]*as_all[i][idx[it]] +
        get_indices(products,idx,as_all,i,it-1);
}

调用

 constexpr std::array<size_t,2> products = {2,0};
 constexpr std::array<size_t,2> idx = {0,1};
 constexpr std::array<std::array<int,3>,8> as_all = {{{0, 0, 0}, 
      {0, 0, 1}, 
      {0, 1, 0}, 
      {0, 1, 1}, 
      {1, 0, 0}, 
      {1, 0, 1}, 
      {1, 1, 0}, 
      {1, 1, 1}}};

get_indices(products,idx,as_all,4,2); // call it

它产生垃圾结果。我认为这是无符号溢出的问题,但我不太确定它是如何发生的。我查看了gccclang

1 个答案:

答案 0 :(得分:2)

你有一个越界访问权限,clang和gcc甚至告诉你:

live example

main.cpp:28:15: error: constexpr variable 'x' must be initialized by a constant expression

constexpr int x = get_indices(products,idx,as_all,4,2);
              ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

main.cpp:11:9: note: read of dereferenced one-past-the-end pointer is not allowed in a constant expression
        products[it]*as_all[i][idx[it]] +
        ^

问题是您尝试访问idx[2]而其大小为2,因此您只能访问idx[0]idx[1]