在 C++ 中,new 分配内存失败时的行为分两种情况,但不会返回 std::bad_alloc
-
默认
new(抛出异常版本)
当内存分配失败时,会抛出std::bad_alloc异常(而非返回该异常对象)。此时不需要检查指针是否为空,而是通过try-catch捕获异常。1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
try {
// 尝试分配超大内存,可能失败
int* arr = new int[1000000000000]; // 分配失败时抛出 std::bad_alloc
delete[] arr;
} catch (const std::bad_alloc& e) {
// 捕获异常并处理
std::cerr << "分配失败:" << e.what() << std::endl;
}
return 0;
} -
nothrow版本的new
使用new (std::nothrow)时,分配失败不会抛出异常,而是返回nullptr(空指针),需要手动检查指针有效性。1
2
3
4
5
6
7
8
9
10
11
12
13
int main() {
// 不抛出异常的版本,失败返回 nullptr
int* arr = new (std::nothrow) int[1000000000000];
if (arr == nullptr) {
std::cerr << "分配失败" << std::endl;
} else {
delete[] arr;
}
return 0;
}
-
普通
new失败时抛出std::bad_alloc异常,需用try-catch处理。 -
new (std::nothrow)失败时返回nullptr,需手动判断指针是否为空。 -
两种情况都不会“返回
bad_alloc”,bad_alloc是异常类型,而非返回值。