2016-06-10 65 views
0

C++標準是否說std::initializer_list<T>是對本地匿名數組的引用?如果它說,那麼我們不應該返回這樣一個對象。標準中的任何部分都這樣說?C++ 11:std :: initializer_list存儲匿名數組嗎?它是否可變?

另一個問題,是std::initializer_list<T>可變的潛在對象?我試圖修改它:

#include <initializer_list> 
int main() 
{ 
    auto a1={1,2,3}; 
    auto a2=a1;//copy or reference? 
    for(auto& e:a1) 
     ++e;//error 
    for(auto& e:a2) 
     cout<<e; 
    return 0; 
} 

但隨着錯誤編譯:錯誤:只讀參考「E」

我怎樣才能解決這個問題,如果我想更改initializer_list內部值的增量?

+0

'initializer_list'是不可變的。 –

回答

5

從[dcl.init.list]:

An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E , where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array.

這應該回答這兩個您的問題:複製initializer_list不復制的基本元素,而下面的元素是const,所以你不能修改它們。

How can I fix it if I wish to change the value inside the initializer_list ?

請勿使用initializer_list<int>。使用array<int, 3>vector<int>或其他容器。

0

cppreference文章

Copying a std::initializer_list does not copy the underlying objects. 
相關問題