【问题标题】:Fixed-size array of objects and sub-objects on the heap [duplicate]堆上固定大小的对象和子对象数组[重复]
【发布时间】:2014-09-17 22:51:46
【问题描述】:

我搜索了又搜索,但没有找到任何真正解决我困惑的东西。

我代表一个网格,并且有两个类,例如:

class Term {
   ...
};

class GridPoint{
   Term a;
   Term b;
   Term c;
   ...
};

我想在堆上有一个固定大小的大型数组,其中数组的每个元素都是一个 GridPoint,它本身包含多个术语。

但是,以下示例将无法编译:

GridPoint* pGrid = new GridPoint[100][100];

根据 gcc:

错误:初始化时无法将‘GridPoint (*)[100]’转换为‘GridPoint*’

【问题讨论】:

  • auto *pGrid = new GridPoint[100][100];

标签: c++ arrays heap-memory


【解决方案1】:

首先我想建议 不要 在现代 C++ 中使用 newdelete,而是使用 智能指针 或标准库中将其封装为的容器例如std::vector.

话虽如此,要让您的示例正常工作,您必须像这样在循环中初始化数组数组:

GridPoint** pGrid = new GridPoint*[100];
for (std::size_t i = 0; i != 100; ++i) {
    pGrid[i] = new GridPoint[100];
}

// Do something...

for (std::size_t i = 0; i != 100; ++i) {
    delete[] pGrid[i];
}
delete[] pGrid;

为了更好的选择,只需使用std::arraystd::vector

std::array<std::array<GridPoint, 100>, 100> pGrid;

注意:std::array 封装了一个静态数组,用于存储其数据。这意味着,如果您分配具有自动存储持续时间的 std::array 对象,则其数据将不会动态分配(数据不会在“堆”上)。

std::vector 将使用动态分配存储其数据。

【讨论】:

  • std::array 不是“在堆上”
  • @MattMcNabb 是的,你是对的,我提供了一个 std::array 用法示例,因为它与使用原始内存分配语法相比显示了它的简单性。
  • -1 用于首先呈现 new[]delete[]
  • @Puppy 好的,为答案添加了一些“正确性”。
猜你喜欢
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2010-10-31
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
相关资源
最近更新 更多