如何使用 new 运算符检查内存分配失败?
就在最近,我将项目的语言从 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.
从我的谷歌搜索中,我没有看到如下所示.
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
}
<小时>
我的回答是指智能指针传播异常.因此,如果您使用普通的 throw new 分配内存,则必须捕获异常.如果您使用 nothrow new 进行分配,那么您必须检查 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
相关文章