什么时候适合使用 C++ 例外情况?
我正在尝试设计一个需要动态分配一些内存的类。
我本来计划在构造期间分配它所需的内存,但是如何处理失败的内存分配? 我应该抛出异常吗? 我在某处读到,异常只能用于“异常”情况,而内存不足对我来说似乎并不是一个异常情况。
我应该在单独的初始化例程中分配内存并检查故障,然后销毁优雅地类实例?
或者我应该使用异常? 如果这些内存分配失败,该类将没有任何有用的事情可做。
编辑:共识似乎是内存不足是一种例外情况。
将看看如何解决这个问题..谢谢..:)
I'm trying to design a class that needs to dynamically allocate some memory..
I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..
Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully?
Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail..
EDIT: The consensus seems to be that running out of memory IS an exceptional case.
Will see how to go about this.. Thanks.. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您使用 new 来分配内存,并且没有重写 new 运算符,那么如果无法正确分配内存,它将自动抛出 std::bad_alloc 异常。
内存不足对我来说似乎是一个非常特殊的情况:)
处理这种情况非常困难。 您可能希望向应用程序的用户返回一个有意义的错误,但如果这是由于内存不足引起的问题,您甚至可能无法负担内存来分配错误消息。 这确实有点像第 22 条军规的情况。
有一种防御性编程技术(有时称为内存降落伞或雨天基金),您可以在应用程序启动时分配一块内存。 然后,当您处理 bad_alloc 异常时,您可以释放该内存,并使用可用内存正常关闭应用程序,包括向用户显示有意义的错误。 这比崩溃要好得多:)
Assuming you are using new to allocate memory, and are not overriding the
new
operator, it will automatically throw thestd::bad_alloc
exception if it fails to allocate memory properly.Running out of memory seems like a pretty exceptional case to me :)
It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.
There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the
bad_alloc
exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)我认为内存不足(特别是堆内存)是一种例外情况,如果您的类 - 以及您的应用程序 - 无法继续,我认为异常抛出/处理是一种非常合适且优雅的方法。
I would argue that running out of memory (particularly heap memory) is an exceptional case, and if your class - and further, your application - cannot continue, I think exception throwing/handling is a very appropriate and graceful approach.
当内存不足时,C++ 中的常见行为是抛出异常。 内置的 new 运算符默认执行此操作。
The usual behaviour in C++ when you are out of memory is to throw an exception. The built-in
new
operator does this by default.