捕获std :: bad_alloc的策略 [英] Policy with catching std::bad_alloc

查看:1144
本文介绍了捕获std :: bad_alloc的策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用Qt很多与我的发展和爱。 Qt对象的通常设计模式是使用 new 分配它们。

So I use Qt a lot with my development and love it. The usual design pattern with Qt objects is to allocate them using new.

几乎所有的例子由Qt设计器生成的代码)绝对不检查 std :: bad_alloc 异常。由于分配的对象(通常是窗口小部件等)很小,这几乎不是问题。毕竟,如果你不能分配20个字节,赔率是没有太多你可以做的来解决这个问题。

Pretty much all of the examples (especially code generated by the Qt designer) do absolutely no checking for the std::bad_alloc exception. Since the objects allocated (usually widgets and such) are small this is hardly ever a problem. After all, if you fail to allocate something like 20 bytes, odds are there's not much you can do to remedy the problem.

目前,我采取了一项政策在try / catch中包装大分配(一页或两个大小)。如果失败,我向用户显示一条消息,几乎任何更小的,我只是让应用程序崩溃与 std :: bad_alloc 异常。

Currently, I've adopted a policy of wrapping "large" (anything above a page or two in size) allocations in a try/catch. If that fails, I display a message to the user, pretty much anything smaller, I'll just let the app crash with a std::bad_alloc exception.

所以,我不知道这方面有什么想法?

So, I wonder what the schools of thought on this are on this?

这是一个好的政策,检查每一个 new 操作?

Is it good policy to check each and every new operation? Or only ones I expect to have the potential to fail?

此外,当处理嵌入式环境时,显然是一个完全不同的故事,在这种环境中,资源可能受到更多限制。我在桌面应用程序的上下文中询问,但也会对涉及其他方案的解答感兴趣。

Also, it is clearly a whole different story when dealing with an embedded environment where resources can be much more constrained. I am asking in the context of a desktop application, but would be interested in answers involving other scenarios as well.

推荐答案

如果你想检查,而不是用包装, try catch 你最好使用

If you want to check, instead of wrapping with try catch you'd better use

    #include <new>
    x = new (std::nothrow) X();
    if (x == NULL) {
        // allocation failed
    }


$ b b

我通常的做法是

My usual practice is


  • 在非交互式程序中,在主级捕获显示一个足够的错误消息。

  • in non interactive program, catch at main level an display an adequate error message there.

在具有用户交互循环的程序中,我也捕获循环,以便用户可以关闭一些东西并尝试继续。

in program having a user interaction loop, I catch also at the loop so that the user can close some things and try to continue.

除此之外,还有其他地方的catch是有意义的,但很少见。

Exceptionally, there are other places where a catch is meaningful, but its rare.

这篇关于捕获std :: bad_alloc的策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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