簡體   English   中英

如果不夠就拋出 Bad_alloc 異常 memory

[英]Throw Bad_alloc exception if not enough memory

我只需要確保我有足夠的 memory 可用於二維數組 map。所以我想我必須在 map 的每一行中放置一個 try catch bad:alloc 或者也許沒有 throw 會更優雅。 但我受不了。 任何幫助,將不勝感激...

我讀過一些關於寫類似的文章:

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

我不喜歡這個解決方案,而且我讀到它不是很可靠。 fillmaze 是在迷宮的構造函數中調用的 function..

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 不夠吧? 我在 class 的析構函數中做:

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

        delete[] map;
}

這就是您應該使用std::vector<>的原因,因為它將正確處理所有 memory 管理。

問題 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

}

你的析構函數正在用餐。


但是您可以通過簡單地使用向量來簡化它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM