2016-07-26 69 views
-2

我有下面的遞歸函數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

+3

請向我們展示一個完整的獨立程序,其輸出顯示問題以及實際輸出。 –

+2

爲什麼人們不能再遵循簡單的指示?總是必須要求一個MCVE。嘆。 –

回答

2

你有一個徹頭徹尾的越界訪問,鐺和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]