如何使用new运算符检查内存分配失败? [英] How to check memory allocation failures with new operator?
问题描述
刚刚我把我的项目的语言切换到使用C的C ++。
使用C,我使用malloc,然后检查malloc是否成功,但是使用C ++,我使用'new'分配内存和我想知道如何通常检查内存分配失败。
Just recently I switched the language of my project to use C++ from C. With C, I used malloc and after that I check if malloc was successful but with C++, I use 'new' to allocate memory and I would like to know how you would normally check the memory allocation failure.
从我的google搜索,我看到不喜欢以下。
From my google search, I saw nothrow like the following.
char *buf = new (nothrow)char[10];
我也看到了以下内容。
try{} catch(bad_alloc&) {}
关于以下?我使用一些chrome库例程来使用智能指针。
But what about the following? I am using some of chrome library routines to use smart pointers.
例如,我的代码如下。
scoped_array<char> buf(new char[MAX_BUF]);
使用智能指针是很好的,但我只是不知道如何检查内存分配那是成功的。
我需要用nothrow或try / catch分成两个单独的语句吗?
如何通常在C ++中执行这些检查?
It is great to use smart pointers but I am just not sure how I should check if the memory allocation was successful. Do I need to break into two separate statement with nothrow or try/catch? How do you normally do these checks in C++?
任何建议都将被感激。
推荐答案
好吧,你调用new会抛出 bad_alloc
,所以你必须赶上:
Well, you call new that throws bad_alloc
, so you must catch it:
try
{
scoped_array<char> buf(new char[MAX_BUF]);
...
}
catch(std::bad_alloc&)
{
...
}
或
scoped_array<char> buf(new(nothrow) char[MAX_BUF]);
if(!buf)
{
//allocation failed
}
b $ b
我的回答是什么意思是智能指针传播异常。所以如果你用普通的throwing new分配内存,你必须捕获异常。如果你分配一个nothrow新,你必须检查 nullptr
。在任何情况下,智能指针不会添加任何东西到这个逻辑
What I mean by my answer is that smart pointers propagate exceptions. So if you're allocating memory with ordinary throwing new, you must catch an exception. If you're allocating with a nothrow new, then you must check for nullptr
. In any case, smart pointers don't add anything to this logic
这篇关于如何使用new运算符检查内存分配失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!