Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何通过分配器为int a[10][10]分配内存_C++_Memory Management - Fatal编程技术网

C++ 如何通过分配器为int a[10][10]分配内存

C++ 如何通过分配器为int a[10][10]分配内存,c++,memory-management,C++,Memory Management,我知道如何通过分配器创建1d数组(如a[10])。例如,这里有一个摘要: #包括 #包括 #包括 int main() { std::分配器a1;//ints的默认分配器 int*a=a1.分配(10);//10个int的空间 a[9]=7; std::cout您可以使用y*10+x来分配100和访问。这就是编译器为[10][10]生成索引的方式 int* a = allocate(100); a[5*10 + 2] = 9; //a[5][2] int[10][10]是一种由10个元素组成的

我知道如何通过分配器创建1d数组(如
a[10]
)。例如,这里有一个摘要:

#包括
#包括
#包括
int main()
{
std::分配器a1;//ints的默认分配器
int*a=a1.分配(10);//10个int的空间
a[9]=7;

std::cout您可以使用y*10+x来分配100和访问。这就是编译器为[10][10]生成索引的方式

int* a = allocate(100);
a[5*10 + 2] = 9; //a[5][2]

int[10][10]
是一种由10个元素组成的数组类型。元素类型是
int[10]
。因此该分配的等价物是:

std::allocator<int[10]> a2;
int (*a)[10] = a2.allocate(10);
std::分配器a2;
int(*a)[10]=a2.分配(10);
您可以使用类型别名简化代码,例如:

using A = int[10];
std::allocator<A> a2;
A *a = a2.allocate(10);
使用A=int[10];
分配器a2;
A*A=a2.分配(10);

请注意,cppreference示例错误地继续写入
a[9]=7;
allocate
函数分配存储,但不在存储中创建对象。(标准明确说明了这一点,C++14表28)。对于不指定对象的左手操作数,使用赋值运算符是一种未定义的行为。在使用赋值运算符之前,您需要随后使用placement new来创建对象。该示例现已修复为使用
construct
而不是
allocate

,如果e数组是固定的,那么您只需编写

int a[10][10]; 
而对于局部变量,分配将在堆栈上,对于全局变量,分配将在数据或bss段中(取决于是否初始化数组成员)

如果您想动态分配数组的大小,我建议使用而不是数组

std::vector<std::vector<int>> a(10, std::vector<int>(10)); 
std::vector a(10,std::vector(10));
std::vector
还可以使用第二个模板参数来定义与
std::allocator
不同的分配器。请注意,内存不是连续分配的


描述了使用连续数组大小的动态大小2D数组的可能性。

这不是
C
。int的生存期从分配存储时开始:[basic.life]p1。1@Cubbi该部分意味着,如果执行了创建int对象的代码,则该int对象生命周期的起始点就是分配存储的点。仅分配存储不会创建任何特定的对象。如果malloc 4字节,则会在图片中创建int或float吗?(我看到有人争辩说,它会在所有可能的4字节对象上叠加一个!)无论如何,我不希望在评论中有这个论点,我会让你参考标准参考和讨论H,那个讨论。我认为与C的无偿不兼容是一个缺陷,但我同意最好调用分配器::construct there,不管怎样..cppreference更新了,谢谢。@M.M我非常感谢你对我的评论和警告您只需在cppreference中指出一个示例,并希望您完整地编写代码(包括使用int(*a)[10]=a2.allocate(10))正确创建一个对象,谢谢您
std::vector<std::vector<int>> a(10, std::vector<int>(10));