如果内存不足,抛出Bad_alloc异常

Throw Bad_alloc exception if not enough memory

本文关键字:alloc 异常 Bad 抛出 内存不足 如果      更新时间:2023-10-16

我只需要确保我有足够的内存可用于二维数组映射。所以我认为我必须在每一行地图中添加一个try catch bad:alloc,或者可能不添加throw会更优雅。但是我不能接受它。如有任何帮助,我将不胜感激。

我读过一些关于写这样的东西的文章:

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

我不喜欢这个解决方案,而且我读到过它不太可靠。Fillmaze是在maze的构造函数内部调用的函数。

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 []图也不够对吧?我在类的析构函数中做的事情:

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

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

问题1:new永远不会返回NULL(对于学弟,下面使用的是正常的new)。另外,在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.


但是你可以通过简单地使用一个向量来简化它:

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