在 C++ 中,如果必须在编译时确定大小,std::array 的意义何在?

Pla*_*ove 7 c++ c++11 stdarray

请原谅我的无知,在我看来,这std::array意味着您的常规数组的 STL 替代品。但是因为数组大小必须作为模板参数传递,它阻止我们std::array使用仅在运行时已知的大小进行创建。

std::array<char,3> nums {1,2,3}; // Works.

constexpr size_t size = 3;
std::array<char,size> nums {1,2,3}; // Works.

const buf_size = GetSize();
std::array<char, buf_size> nums; // Doesn't work.
Run Code Online (Sandbox Code Playgroud)

我认为 C++ 中数组的一个非常重要的用例是基于运行时输入创建一个固定大小的数据结构(比如为读取文件分配缓冲区)。

我为此使用的解决方法是:

// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;
Run Code Online (Sandbox Code Playgroud)

或者:

// Use unique_ptr as a class member and I don't want to manage the memory myself.
std::unique_ptr<char[]> myarr_ = std::unique_ptr<char[]>(new char[size]);
Run Code Online (Sandbox Code Playgroud)

如果我不关心固定大小,我知道我可以使用std::vector<char>预定义的大小,如下所示:

std::vector<char> my_buf (buf_size);
Run Code Online (Sandbox Code Playgroud)

为什么设计者std::array选择忽略这个用例?也许我不了解std::array.

编辑:我想表达我的问题的另一种方式也可能是 - 为什么设计师选择将大小作为模板参数而不是作为构造函数参数传递?选择后者是否会使提供std::array目前具有的功能变得困难?对我来说,这似乎是一个深思熟虑的设计选择,我不明白为什么。

iam*_*ind 9

易于编程

std::array促进了在std::vector. 对于普通的 C 风格数组,不能有.size()(no sizeofhack), .at()(out of range), front()/back(), 迭代器等。一切都必须手工编码。

许多程序员std::vector甚至可能在编译时选择已知大小的数组,仅仅因为他们想利用上述编程方法。但这会剥夺编译时固定大小数组的可用性能。
因此std::array,由库制造商提供以阻止 C 样式数组,但std::vector在编译时已知大小时避免使用s。

  • 堆栈分配意味着数组的数据存储在对象本身中。但这意味着“sizeof(runtime_sized_array)”不能是编译时常量,这会破坏很多东西。例如,如何堆栈分配 `std::Optional&lt;runtime_sized_array&lt;int&gt;&gt;`?您将如何实现“std::vector&lt;runtime_sized_array&lt;int&gt;&gt;”?或者甚至是`runtime_sized_array&lt;int&gt;two_arrays[2]{runtime_sized_array&lt;int&gt;(5),runtime_sized_array&lt;int&gt;(7)}`?如果你有 `runtime_sized_array&lt;int&gt;* p`,那么 `p++` 会做什么? (2认同)