在C ++新指令中检查异常的频率是多少? [英] How often do you check for an exception in a C++ new instruction?

查看:105
本文介绍了在C ++新指令中检查异常的频率是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始阅读Effective C ++,并且达到了作者谈论运算符的新点。



这本书很好地解释了如何捕获各种程度的优雅)std :: bad_alloc异常,如果你内存不足,运算符new可以提高。



我的问题是: case没有足够的内存来实例化一个对象,如果有的话?为什么?

解决方案

我可以回答这个问题时捕获异常:


$


大多数时候,我的回答是,我不知道,也许我的调用者知道。所以我不抓住异常。



当你遇到一个异常,让你的函数继续运行时,你已经对你的程序说,没关系,一切都在罚款这里。当你说,通过golly,一切都更好。所以,如果你已经耗尽内存,那么在你处理了 std :: bad_alloc 后,你不应该再失去内存了。你不应该只从你的函数返回一个错误代码,因为然后调用程序必须明确检查该错误代码,你还是内存不足。您的处理该异常应释放一些内存。清空一些缓存,将一些东西提交到磁盘等。但是,你的程序中有多少功能真的要负责减少程序的内存使用?



如果你不能解决触发异常的问题,那么不要处理异常。


I just started reading Effective C++ today and got to the point where the author talks about the operator new.

The book explains very well how you can catch (with various degrees of elegance) the std::bad_alloc exception that the operator new can raise if you run out of memory.

My question is: How often do you check for the case when there isn't enough memory to instantiate a object, if at all? and why? Is it worth the hassle?

解决方案

I catch exceptions when I can answer this question:

What will you do with the exception once you've caught it?

Most of the time, my answer is, "I have no idea. Maybe my caller knows." So I don't catch the exception. Let it bubble up to someone who knows better.

When you catch an exception and let your function proceed running, you've said to your program, "Never mind. Everything's fine here." When you say that, by golly, everything had better be fine. So, if you've run out of memory, then after you've handled std::bad_alloc, you should not be out of memory anymore. You shouldn't just return an error code from your function, because then the caller has to check explicitly for that error code, and you're still out of memory. Your handling of that exception should free some memory. Empty some caches, commit some things to disk, etc. But how many of the functions in your program do you really want to be responsible for reducing your program's memory usage?

If you cannot solve the problem that triggered the exception, then do not handle the exception.

这篇关于在C ++新指令中检查异常的频率是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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