[英]How to properly init a vector of std::array?
首先,我有一個模板數據結構,可以使用數字索引訪問元素。 索引可以為負。
class RangeList
{
public:
RangeList(PosType off_min, PosType off_max)
: _off_min(off_min)
, _off_max(off_max)
, data(off_max - off_min + 1) {}
T& operator[] (PosType i)
{ return data[i-_off_min]; }
const T& operator[] (PosType i) const
{ return data[i-_off_min]; }
size_t size()
{ return data.size(); }
protected:
PosType _off_min;
PosType _off_max;
std::vector<T> data;
};
我使用C ++ 11 std :: array表示一些固定長度的數據配置文件:
typedef std::array<float, std::numeric_limit<uint16_t>::max()> ProfileType;
當這兩件事結合在一起時,就會出現問題:
typedef RangeList<ProfileType> ProfileRangeList;
在RangeList
內部, data
成員的類型為vector<array<float, 65536> >
。
我注意到,如果在堆棧上創建std :: array,則其內容將未初始化,並且需要將其內容顯式設置為零。 那么,如果std :: array是std :: vector的值類型,會發生什么呢?
在我的測試代碼中,似乎內容被神奇地初始化為零,但是我不知道它是否符合語言標准並且可靠且可復制。
我想如果您在堆棧上創建array
意味着類似於以下內容:
std::array<T,s> arr;
但是,這也是有效的:
std::array<T,s> arr {};
這將對每個字段進行值初始化。 這就是vector
(對其每個array
元素)的作用,因此您很安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.