简体   繁体   English

如何正确初始化std :: array的向量?

[英]How to properly init a vector of std::array?

Firstly, I have a template data structure which can access elements using numeric indices. 首先,我有一个模板数据结构,可以使用数字索引访问元素。 The indices can be negative. 索引可以为负。

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;
};

I use C++11 std::array to represent some data profile of fixed length: 我使用C ++ 11 std :: array表示一些固定长度的数据配置文件:

typedef std::array<float, std::numeric_limit<uint16_t>::max()> ProfileType;

The question raises when these two things combined together: 当这两件事结合在一起时,就会出现问题:

typedef RangeList<ProfileType> ProfileRangeList;

Inside RangeList , the data member will be of type vector<array<float, 65536> > . RangeList内部, data成员的类型为vector<array<float, 65536> >

I noticed, if you create a std::array on the stack, its contents will be uninitialized, and you need to explicitly set its content to zero. 我注意到,如果在堆栈上创建std :: array,则其内容将未初始化,并且需要将其内容显式设置为零。 So what happens if the std::array is a value type of std::vector? 那么,如果std :: array是std :: vector的值类型,会发生什么呢?

In my test code, it seems the contents are magically initialized to zeroes, but I don't know if it obeys language standard and is reliable and reproducible. 在我的测试代码中,似乎内容被神奇地初始化为零,但是我不知道它是否符合语言标准并且可靠且可复制。

I suppose your If you create array on the stack means something akin to: 我想如果您在堆栈上创建array意味着类似于以下内容:

std::array<T,s> arr;

This is also valid, though: 但是,这也是有效的:

std::array<T,s> arr {};

Which will value-initialize every field. 这将对每个字段进行值初始化。 And that's what vector does (to each of its array elements), so you're safe. 这就是vector (对其每个array元素)的作用,因此您很安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM