在 C++11 中,我们有一个新std::array的boost::array. 例子:
std::array<int, 5> fiveInts;
如果我想以两种方式使用这个新数组:
- 在堆栈上分配一个数组。
- 在堆上分配一个数组。
如何在语法上实现这一点?那5可以是一个变量还是只是一个const?
std::array<int, 5> fiveInts;
在堆栈上分配一个数组(自动存储)。
std::array<int,5>* fiveInts = new std::array<int, 5>;
在堆上分配一个数组(动态存储)。
该值必须在编译时知道,是的。
模板参数必须始终在编译时已知。a 的大小std::array不能是变量。
管理堆上的值的连续缓冲区的最佳方法是 via std::vector,它为您提供缓冲区大小的运行时大小。
std::array<int, 5> fiveInts;在堆栈上创建一个包含 5 个元素的数组(在自动存储中)。 在堆上(在空闲存储中)std::vector<int> fiveInts(5);创建一个 5 秒的托管缓冲区。int
您可以std::array通过调用在堆上创建完整的new,但我建议不要这样做。 std::array它的主要优点是它允许基于堆栈(或基于内部到类)的存储。
std::array<T, N>是一个由Ntype 对象组成的模板T。您可以创建这种类型的自动对象:
void f() {
std::array<int, 5> auto_ints;
}
并且该对象将包含 5 个 int 对象,全部在堆栈中。
您还可以在免费商店中创建这种类型的对象:
void g() {
std::array<int, 5> *free_store_ints = new std::array<int, 5>;
}
但几乎没有理由这样做,因为std::vector<int>它做得更好。
您必须在std::array编译时指定大小;您可以在运行时std::vector调整大小。