C++ new错误处理

在C++中处理内存分配错误大概有两种方法:

  • 使用try...catch
#include <iostream>

int main(void) {
    try {
        long long int n = 1024 * 1024 * 1024, m = 1024 * 1024;
        auto a = new int[n * m];
    } catch(std::bad_alloc &e) {
        std::cout << "catch bad_alloc exception" << std::endl;
    } catch(std::exception &e) {
        std::cout << e.what() << std::endl;
    } catch(...) {
        std::cout << "unknow error" << std::endl;
    }

    return 0;
}
  • 使用nothrow, 错误处理流程与C语言一样
#include <iostream>

int main(void) {
    long long int n = 1024 * 1024 * 1024, m = 1024 * 1024;
    auto a = new(std::nothrow) int[n * m];
    if (a == nullptr) {
        std::cout << "nullptr" << std::endl;
    }

    return 0;
}

如果觉得有帮助,可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *