我知道如何通过分配器创建一维数组(如a[10]
)。例如,这是来自 cppreference 的摘要:
#include <memory>
#include <iostream>
#include <string>
int main()
{
std::allocator<int> a1; // default allocator for ints
int* a = a1.allocate(10); // space for 10 ints
a[9] = 7;
std::cout << a[9] << '\n';
// the remainder was omitted .....
return 0;
}
但是,我不知道如何创建二维数组,例如 int a[10][10]
。有人可以帮我吗?
最佳答案
int[10][10]
是一个包含 10 个元素的数组类型。元素类型为int[10]
。因此,该分配的等价物是:
std::allocator<int[10]> a2;
int (*a)[10] = a2.allocate(10);
您可以使用类型别名来简化代码,例如:
using A = int[10];
std::allocator<A> a2;
A *a = a2.allocate(10);
请注意,cppreference 示例错误地继续写入 a[9] = 7;
。 allocate
函数分配存储空间,但不会在存储空间中创建对象。 (标准明确指出了这一点,C++14 表 28)。将赋值运算符与未指定对象的左侧操作数一起使用是未定义的行为。在使用赋值运算符之前,您随后需要使用placement-new来创建对象。该示例现已修复为使用 construct
而不是 allocate
。
关于c++ - 如何通过分配器为 int a[10][10] 分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43585018/