如果内存不足,抛出Bad_alloc异常
Throw Bad_alloc exception if not enough memory
我只需要确保我有足够的内存可用于二维数组映射。所以我认为我必须在每一行地图中添加一个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};
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- 尝试解决HackerBank上的BFS挑战时出现错误的alloc异常