简体   繁体   中英

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

If new cannot find enough memory, it throws an exception. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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