gpt4 book ai didi

c++ - 处理 3rd 方库内存不足导致的崩溃

转载 作者:行者123 更新时间:2023-11-28 07:28:04 25 4
gpt4 key购买 nike

如果使用 new 动态分配大量内存,程序可能会崩溃,因为 new 返回 NULL。使用异常,可以捕获 std::bad_alloc 并做最适合的事情:

try{
allocate_much_memory();
catch( std::exception e){
do_something_that_fits();
}

如果出于某种原因不能使用异常,则需要检查 NULL:

BigBlob* allocate_much_memory(){
BigBlob *bblob = new BigBlob();
if( bblob == NULL ){
std::cerr << "uh-oh" << std::endl;
handle_error();
}
return bblob;
}

关键是,据我所知,您必须自己编写 NULL 检查。 如果您不能更改该函数,因为它来自第三方库,并且您不使用异常,您该怎么办?

更新:对于我正在检查 new BigBlob() 的结果是否为 NULL 的部分:没有必要:见Do I need to check for NULL after p = new Fred()? How can I convince my (older) compiler to automatically check new to see if it returns NULL?

最佳答案

如果他们抛出异常,你去这里:

Global exception handling in C++

如果他们不这样做,你就完蛋了。

这也是有原因的。想想看。你怎么知道这个图书馆的分配在哪里?遇到失败你会怎么做?最后一个特别重要。除了崩溃,你会做什么?

关于c++ - 处理 3rd 方库内存不足导致的崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18346040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com