常见机制
- 检查返回值:在使用
new
分配内存时,new
会在分配失败时抛出std::bad_alloc
异常。也可以使用new (std::nothrow)
形式,这种情况下分配失败返回nullptr
,通过检查返回值判断是否分配成功。
- 异常处理:使用
try - catch
块捕获std::bad_alloc
异常,在catch
块中进行错误处理,比如输出错误信息、释放已分配的资源等。
代码示例
#include <iostream>
#include <cstdlib>
// 使用new (std::nothrow) 检查返回值方式
int* createIntArray(size_t size) {
int* arr = new (std::nothrow) int[size];
if (!arr) {
std::cerr << "Memory allocation failed!" << std::endl;
return nullptr;
}
return arr;
}
// 使用异常处理方式
int* createIntArrayWithException(size_t size) {
try {
int* arr = new int[size];
return arr;
} catch (const std::bad_alloc& e) {
std::cerr << "Memory allocation failed: " << e.what() << std::endl;
return nullptr;
}
}
int main() {
int* arr1 = createIntArray(1000000000); // 可能导致内存分配失败
if (arr1) {
// 使用数组
delete[] arr1;
}
int* arr2 = createIntArrayWithException(1000000000);
if (arr2) {
// 使用数组
delete[] arr2;
}
return 0;
}