请原谅我的无知,在我看来这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.
我认为C ++中数组的一个非常重要的用例是根据运行时输入(例如,分配缓冲区以读取文件)创建固定大小的数据结构。
我为此使用的解决方法是:
// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;
要么:
// 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]);
如果我不在乎固定大小,那么我知道我可以使用std::vector<char>
预先定义的大小,如下所示:
std::vector<char> my_buf (buf_size);
为什么std::array
选择的设计师选择忽略此用例?也许我不了解的真正用例std::array
。
编辑:我想表达我的问题的另一种方式也可能是-为什么设计师选择将大小作为模板参数而不是构造函数参数传递?选择后者会难以提供std::array
当前具有的功能吗?对我来说,这似乎是一个故意的设计选择,我不明白为什么。
std::array
有助于在中使用的几个有益的接口和习惯用法std::vector
。对于普通的C样式数组,不能有.size()
(没有sizeof
hack),.at()
(超出范围的例外)front()/back()
,迭代器等。一切都必须手工编码。
许多程序员std::vector
甚至可能选择编译时已知大小的数组,只是因为他们想利用上述编程方法。但这抢走了编译时固定大小数组的可用性能。
因此std::array
,库制造商提供了阻止C样式数组的方法,但std::vector
在编译时知道大小时避免使用s。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句