New (std::nothrow) vs. New within a try/catch block

前端 未结 4 1660
無奈伤痛
無奈伤痛 2020-12-01 09:12

I did some research after learning new, unlike malloc() which I am used to, does not return NULL for failed allocations, and found there are two di

4条回答
  •  隐瞒了意图╮
    2020-12-01 09:51

    Consider what you are doing. You're allocating memory. And if for some reason memory allocation cannot work, you assert. Which is more or less exactly what will happen if you just let the std::bad_alloc propagate back to main. In a release build, where assert is a no-op, your program will crash when it tries to access the memory. So it's the same as letting the exception bubble up: halting the app.

    So ask yourself a question: Do you really need to care what happens if you run out of memory? If all you're doing is asserting, then the exception method is better, because it doesn't clutter your code with random asserts. You just let the exception fall back to main.

    If you do in fact have a special codepath in the event that you cannot allocate memory (that is, you can actually continue to function), exceptions may or may not be a way to go, depending on what the codepath is. If the codepath is just a switch set by having a pointer be null, then the nothrow version will be simpler. If instead, you need to do something rather different (pull from a static buffer, or delete some stuff, or whatever), then catching std::bad_alloc is quite good.

提交回复
热议问题