简体   繁体   English

每当动态分配内存时,您是否总是必须检查bad_alloc?

[英]Do you always must check for bad_alloc whenever dynamically allocating memory?

If new cannot find enough memory, it throws an exception. 如果new找不到足够的内存,则抛出异常。 Do I absolutely always need to check for that? 我绝对需要检查吗? I never did that and had no issues, but now I've read you should do that. 我从来没有这样做,没有任何问题,但现在我已经读过你应该这样做了。 Or only in certain cases? 或者仅在某些情况下?

try
{
    pPos = new Vector2D(5,1);
}
catch(bad_alloc)
{
    // NO MEMORY!
}

There's nothing special about bad_alloc , you can catch it or not as you would any other exception. bad_alloc没有什么特别之处,您可以像其他任何异常一样捕获它。 It is unusual to catch it. 抓住它是不寻常的 You would only do that if you had some way to recover from the out-of-memory condition. 如果你有某种方法可以从内存不足状态中恢复,那么你只能这样做。 But I think programs that are designed to deal with out-of-memory errors more commonly use the nothrow version of new instead: 但我认为旨在处理内存不足错误的程序更常用的是newnothrow版本:

pPos = new (std::nothrow) Vector2D(5,1);
if (!pPos) {
    // NO MEMORY!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM