c++ - C++11 数组怎么能不存储它的大小呢?

标签 c++ arrays c++11

来自 cplusplus.com :

Internally, an array does not keep any data other than the elements it contains (not even its size, which is a template parameter, fixed on compile time).

我理解这意味着使用 array 类似于在同一范围内使用 int[]sizeof。但是此代码是否有效或依赖于未定义的行为?

class A {
    array<int, 10> arr;
    void setArr() {
        for (int& i : arr)
            i = 42;
    }
    void printArr() {
        for (int i : arr)
            cout << i << endl;
    }
};

编译器如何知道何时停止 foreach 而不将数组大小存储在堆或堆栈上?我运行了它,代码有效。

最佳答案

它说的更多,并且在您的引文中有回应:

[...] not even its size, which is a template parameter, fixed on compile time [...]

例如,下面的代码也是合法的:

template<int N>
struct C {
    int size() { return N; }
};

如您所见,我们在这里做同样的事情,N 无论如何都不会保留,但它是众所周知的模板参数,在编译时固定

这同样适用于模板化类 std::array,它接受定义其大小 的模板参数。因此,大小 在编译时是已知的(并且是固定的)并且它隐含地是生成类型的一部分,即使在运行时没有保留额外的空间也是如此。

编辑(根据评论)

当然,您不能在运行时通过简单地调用其中一种方法来更改此类数组的大小。如前所述here :

std::array is a container that encapsulates fixed size arrays.

此外,动态更改其大小也没有意义,因为它不再与定义实际大小的模板参数保持一致。因此,响应显然是:,您不能更改它的大小(当然,即使您可以使用该数组填充另一个具有不同大小的数组)。

但是,这样做有很多好处:

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

由您决定是否值得使用它来代替普通的 C 风格数组。这主要取决于您面临的问题,所以我不能这么说。

关于c++ - C++11 数组怎么能不存储它的大小呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33981097/

相关文章:

c++ - 如何在没有实例的情况下获取非静态方法的类型?

c++ - 更好的单元测试方法,需要太长时间

c++ - 在第一个可用索引处将对象设置为 C 数组

php - 比较给出不同结果的数组

c++ - 从类方法返回成员 unique_ptr

c++ - 使用类模板需要模板参数列表?

c++ - 制作 shared_ptr 的拷贝时会发生什么?

c++ - 我可以这样使用#undef吗?

C++ 在嵌入式系统中的使用

php切割多维数组