新的(std :: nothrow)与新的在try / catch块 [英] New (std::nothrow) vs. New within a try/catch block

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

问题描述

我在学习 new 后进行了一些研究,不像我过去使用的 malloc() NULL为失败的分配,并且发现有两种不同的方式检查新成功与否。这两种方法是:

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

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

我相信这两种方法可以达到同样的目标,如果我错了, ,所以我的问题是这样:



这是更好的选项,用于检查成功,完全基于可读性,可维护性和性能,而忽略事实上的c ++编程惯例。

解决方案

考虑你在做什么。你正在分配内存。如果由于某种原因内存分配不能工作,你 assert 。如果你只是让 std :: bad_alloc 传播回 main ,那么会发生什么。在发布版本中, assert 是无操作,当程序尝试访问内存时,它会崩溃。



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



如果你事实上在事件中有一个特殊的编码路径你不能分配内存(也就是说,你可以继续运行),异常可能或可能不是一个方法去,取决于编码路径是什么。如果编码路径只是一个指针为null的开关集合,那么 nothrow 版本将会更简单。如果相反,你需要做一些不同的事情(从一个静态缓冲区,或删除一些东西,或其他),然后捕获 std :: bad_alloc 是相当不错。 / p>

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();
};

and

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:

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

解决方案

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.

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.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆