gpt4 book ai didi

c++ - 如果内存不足抛出 Bad_alloc 异常

转载 作者:行者123 更新时间:2023-12-05 07:53:06 25 4
gpt4 key购买 nike

我只需要确保我有足够的内存可用于二维数组映射。所以我想我必须在 map 的每一行中尝试 catch bad:alloc ,或者可能没有 throw 会更优雅。但我受不了。任何帮助将不胜感激...

我读过一些关于编写类似内容的文章:

 map[i] = new int [columns];
if (map[i] == NULL)
cout << “No enough memory”;

我不喜欢这个解决方案,而且我读到它不是很可靠。fillmaze 是在迷宫的构造函数中调用的函数..

void Maze::setupMaze(int r, int c, int l){
rows = r;
columns = c;
level = l;

fillMaze();
addBorders();
centerWalls();
getaway();
addWalls();
}
void Maze::fillMaze(){

map = new int* [rows];
for (int i = 0; i < rows; i++) {
map[i] = new int[columns];
}

//Inicializamos toda la tabla
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
map[i][j] = PASSAGE;
}
}
}

此外 delete [] map 还不够吗?我正在类的析构函数中做:

Maze::~Maze(void)
{
for (int i = 0; i < rows; ++i)
delete[] map[i];

delete[] map;
}

最佳答案

这就是为什么你应该使用 std::vector<>因为它将为您正确处理所有内存管理。

第 1 期:new永不返回 NULL (对于学徒来说,下面使用的是正常的新)。另请注意,在 C++ 中我们使用 nullptr不是NULL为了类型安全。

 map[i] = new int [columns];
if (map[i] == NULL) // This will never be NULL
cout << “No enough memory”; // So this will never print anything.

如果fillmaze()从构造函数中调用。然后,如果它抛出异常,则永远不会调用您的析构函数。这意味着您必须就地处理任何分配失败。

    map = new int* [rows];              // could throw.
for (int i = 0; i < rows; i++) {
map[i] = new int[columns]; // could throw
}

因此您必须处理并能够检测已分配的内容以及需要分配的内容。

try
{
map = nullptr; // Init to nullptr to make sure
// you can distinguish between valid state
// and what could have randomly been in memory.

map = new int* [rows]{nullptr}; // Initialize all elements to nullptr.
// If any throw you don't want your code
// to start releasing random pointers.
// calling delete on nullptr is fine.

for (int i = 0; i < rows; i++) {
map[i] = new int[columns]{PASSAGE};
}
}
catch(...) // catch all exceptions.
{
if (map != nullptr) { // You should only loop over
// map if it has been allocated.
for (int i = 0; i < rows; i++) {
delete [] map[i];
}
}
delete [] map; // delete the map.
throw; // rethrow exception

}

你的析构函数是 dine。


但是您可以通过简单地使用 vector 来简化它:

 std::vector<std::vector<int>>   maze{std::vector<int>{PASSAGE, columns}, rows};

关于c++ - 如果内存不足抛出 Bad_alloc 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com