new失败的两种情况

在 C++ 中,new 分配内存失败时的行为分两种情况,但不会返回 std::bad_alloc

  1. 默认 new(抛出异常版本)
    当内存分配失败时,会抛出 std::bad_alloc 异常(而非返回该异常对象)。此时不需要检查指针是否为空,而是通过 try-catch 捕获异常。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <iostream>
    #include <new> // 包含 std::bad_alloc 的定义

    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;
    }
  2. nothrow 版本的 new
    使用 new (std::nothrow) 时,分配失败不会抛出异常,而是返回 nullptr(空指针),需要手动检查指针有效性。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <iostream>
    #include <new>

    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 是异常类型,而非返回值。