什么时候应该使用std :: nothrow? [英] When should std::nothrow be used?

查看:113
本文介绍了什么时候应该使用std :: nothrow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: nothrow

的理想用法是什么? p>我只使用它作为一个优化(或代码简化),否则我会把一个try-catch块立即使用常规新的,捕获 std :: bad_alloc



这是一个非常罕见的情况,因为很少能够在调用站点处有效地处理内存不足。通常你分配内存,因为你需要它,而不是因为你很想拥有它,但可以没有生活。通过空指针的代码备份一个调用者链,直到最终有人可以处理这个问题是不成语的C ++。



这可能发生,虽然错误真的可以立即处理。例如,你可能在一个情况下,你会使用一个算法或技术给予足够的工作空间,和一个不同的,较慢的算法或技术没有。然后,你会直接用 new 分配这样的工作空间吗?不正常。无论如何,你有时必须小心这种方法,因为如果你的操作系统overcommits然后一般来说,你不能在应用程序级别优雅地处理内存。



请注意,涉及std :: nothrow的表达式仍然可以抛出异常(特别是来自正在分配的对象的任何构造函数),因此,如果您希望的话,只需要一个以避免抛出异常。你还必须确保构造函数不会抛出。



就我所关心的C ++程序的日子,根本不使用异常,过度。我想如果他们为我恢复,由于一些特定的风格指南,那么这是需要不新的其他可能的原因。


What is the ideal usage of std::nothrow?

解决方案

I'd use it only as an optimization (or code simplification) when I would otherwise have put a try-catch block immediately around a use of regular new, catching std::bad_alloc.

This is quite a rare situation, because it's rare to be able to usefully handle out-of-memory right there at the call site. Usually you allocate memory because you need it, not because you'd quite like to have it but can live without. Code that passes null pointers back up a chain of callers until eventually someone can deal with the problem isn't idiomatic C++.

It can happen though that the error genuinely can be handled immediately. For example you might be in a situation where you'll use one algorithm or technique given sufficient working space, and a different, slower algorithm or technique without. Then again, would you be allocating such working space directly with new? Not normally. And anyway, you sometimes have to be careful with that approach, because if your OS overcommits then in general you cannot handle out of memory gracefully at the application level.

Note that an expression involving std::nothrow can still throw an exception (in particular from any constructor of the object being allocated), so it's only one thing needed if you're hoping to avoid throwing an exception. You also have to ensure that the constructor won't throw.

As far as I'm concerned the days of C++ programs that don't use exceptions at all, are over. I suppose if they resumed for me, due to some particular style guide, then that's the other likely reason for needing nothrow new.

这篇关于什么时候应该使用std :: nothrow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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