你还在C ++程序中捕获内存分配失败 [英] Do you still trap memory allocation failures in your C++ program
问题描述
我为公司编写了一些指南,我需要回答一些棘手的问题。这一个是相当困难。
I am writing some guidelines for the company and I need to answer some tough questions. This one is quite difficult.
解决方案可以是:
-
确保使用new分配对象,当分配失败时会抛出异常。应用程序将死亡,这不是一个大问题。 PRO - 代码通常可以很干净。
Not track at all. Make sure that objects are allocated using new which will throws an exception when allocation failed. The application will die, and it is not a big deal. PRO - code usually can be very clean.
跟踪内存分配失败并相应报告,就像任何错误(如文件访问错误)。
Track memory allocation failures and reports it accordingly, just like any errors (such as file access error).
老实说,如果我们使用选项2,我必须写更多的代码。例如,许多std :: tring操作涉及内存分配。如
Honestly, I have to write much more code if we go with option 2. For example, many std::tring operations involve memory allocation. Such as
std :: string str1,str2;
strl = str2;
str + = str2;
std::string str1, str2; str1 = str2; str += str2;
我们的软件将始终运行主要平台,而不是嵌入式。不知怎的,我认为选项1是要走的路。
Our software will always run major platforms, not embedded. Somehow I think that option 1 is the way to go. What's your opinion?
推荐答案
我做陷阱内存分配,但只是偶尔。
I do trap memory allocations, but only occasionally.
特别是,我偶尔会捕获内存分配,其中:
In particular, I will occasionally trap a memory allocation where:
- 我知道分配的内存量非常大
- 如果分配失败,我可以做一些事情(即:通过向用户发出通知来优雅地处理条件等)
这就是说,这两个东西是很少见的 - 通常我最后让程序死于异常。
That being said, those two things are pretty rare - usually I just end up letting the program die from the exception.
这篇关于你还在C ++程序中捕获内存分配失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!