在 try/catch 块中新建 (std::nothrow) 与新建

New (std::nothrow) vs. New within a try/catch block(在 try/catch 块中新建 (std::nothrow) 与新建)

本文介绍了在 try/catch 块中新建 (std::nothrow) 与新建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习new后做了一些研究,不像我习惯的malloc(),不会为失败的分配返回NULL,发现有两种不同的方式检查 new 是否成功.这两种方式是:

I did some research after learning new, unlike malloc() which I am used to, does not return NULL for failed allocations, and found there are two distinct ways of checking whether new had succeeded or not. Those two ways are:

try
{
    ptr = new int[1024];
}
catch(std::bad_alloc& exc)
{
    assert();
};

ptr = new (std::nothrow) int[1024];
if(ptr == NULL) 
    assert();

我相信这两种方式可以实现相同的目标,(当然,如果我错了,请纠正我!),所以我的问题是:

I believe the two ways accomplish the same goal, (correct me if I am wrong of course!), so my question is this:

这是检查 new 是否成功的更好选择,完全基于可读性、可维护性和性能,同时无视事实上的 C++ 编程约定.

which is the better option for checking if new succeeded, based entirely on readability, maintainability, and performance, while disregarding de-facto c++ programming convention.

推荐答案

考虑你在做什么.您正在分配内存.如果由于某种原因内存分配不能工作,你assert.如果您让 std::bad_alloc 传播回 main,这或多或少会发生什么.在发布版本中,assert 是空操作,当它尝试访问内存时,您的程序将崩溃.所以这与让异常冒泡一样:停止应用程序.

Consider what you are doing. You're allocating memory. And if for some reason memory allocation cannot work, you assert. Which is more or less exactly what will happen if you just let the std::bad_alloc propagate back to main. In a release build, where assert is a no-op, your program will crash when it tries to access the memory. So it's the same as letting the exception bubble up: halting the app.

所以问自己一个问题:你真的需要关心如果内存不足会发生什么吗?如果您所做的只是断言,那么异常方法会更好,因为它不会用随机的 assert s 弄乱您的代码.您只需让异常回退到 main.

So ask yourself a question: Do you really need to care what happens if you run out of memory? If all you're doing is asserting, then the exception method is better, because it doesn't clutter your code with random asserts. You just let the exception fall back to main.

如果您在无法分配内存的情况下确实有一个特殊的代码路径(也就是说,您实际上可以继续运行),则异常可能是也可能不是一种方法,具体取决于代码路径是什么.如果代码路径只是通过将指针设置为空来设置的开关,那么 nothrow 版本会更简单.如果相反,您需要做一些相当不同的事情(从静态缓冲区中拉取,或删除一些东西,或者其他什么),那么捕获 std::bad_alloc 非常好.

If you do in fact have a special codepath in the event that you cannot allocate memory (that is, you can actually continue to function), exceptions may or may not be a way to go, depending on what the codepath is. If the codepath is just a switch set by having a pointer be null, then the nothrow version will be simpler. If instead, you need to do something rather different (pull from a static buffer, or delete some stuff, or whatever), then catching std::bad_alloc is quite good.

这篇关于在 try/catch 块中新建 (std::nothrow) 与新建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 try/catch 块中新建 (std::nothrow) 与新建

基础教程推荐