[英]What to do if I get std::bad_alloc?
創建有機體類指針的2d
數組:
try{
world = new Organism**[worldSizeX];
for (int x = 0; x < worldSizeX; x++){
world[x] = new Organism*[worldSizeY];
// INITATES world ARRAY
for (int y = 0; y < worldSizeY; y++){
world[x][y] = new Organism;
}
// !INITATES world ARRAY
}
}
catch (std::bad_alloc){
std::cout << "Not enough memory for World size" << worldSizeX << "x" << worldSizeY << std::endl;
deleteWorld(); // DO I NEED THIS?
init((int)worldSizeX/2, (int)worldSizeY/2, ants, beetles);
return;
}
如果我有bad_alloc
我想用較小的int值調用init。 我必須delete
失敗的陣列還是可以重新運行? 如果是的話,那么我該如何刪除它,我無法遍歷整個數組應用程序而崩潰。
當您嘗試deleteWorld
時,程序崩潰的原因是您的數組未完全初始化。 因此,在此過程中,您可能會遇到未初始化的指針。
為了避免這種情況,請對您的數組進行零初始化 :
world = new Organism**[worldSizeX]();
(請注意尾隨()
,它表示數組的零初始化)。
現在,當您實現deleteWorld
,您將不得不跳過所有為NULL的條目。
最后:是的,當您獲取bad_alloc
時,您必須刪除所有內容:某些對象可能已經被分配了,因此,如果在分配時沒有先取消分配,則將發生內存泄漏。
如果您使用向量,則析構函數將被自動調用,因此您將不需要它並且程序不會泄漏
try{
vector< vector < Organism > >world;
world.resize(worldSizeX);
for (int x = 0; x < worldSizeX; x++){
world[x] = vector<Organism>(worldSizeY);//this calls the default constructor so you don't need the second for loop
}
}
catch (std::bad_alloc){
std::cout << "Not enough memory for World size" << worldSizeX << "x" << worldSizeY << std::endl;
init((int)worldSizeX/2, (int)worldSizeY/2, ants, beetles);
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.