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

标签 c++ memory-management

我知道如何通过分配器创建一维数组(如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/

相关文章:

C++ 设计 : reducing coupling in a deep class hierarchy

c++ - 图 - 强连通分量

memory-management - 如何使用保留的CMA内存?

java - 垃圾收集器与池

iphone - 这段代码是否有可能在内存方面引起任何问题?

c++ - 错误 : expected unqualified-id before 'not' token g c++ builder

c++ - 将 C++ 内存文件加载到 Python 中

c++ - GUI框架类的设计

android - 使用弱引用是避免内存泄漏的最佳方法吗?

c++ - (C++) 当函数完成时分配在堆栈上的数组发生了什么?