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

标签 c++ exception-handling dynamic-arrays bad-alloc

我只需要确保我有足够的内存可用于二维数组映射。所以我想我必须在 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/

相关文章:

PHP - 生产环境的明智/优雅/优雅的错误处理

Ruby:捕获异常后继续循环

c - 动态分配数组说明

c++ - 特化一个模板类?

c++ - C++中的命名参数字符串格式

c++ - 无法编译 curlpp

c++ - 未处理的 Win32 异常

multidimensional-array - 系统验证 : associative array of dynamic arrays

c++ - 调试断言失败!表达式: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

c++ - char* p=NULL, cout<<p;给出异常(exception)