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

前端 未结 4 1666
無奈伤痛
無奈伤痛 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:44

    It depends on the context of where the allocation is taking place. If your program can continue even if the allocation fails (maybe return an error code to the caller) then use the std::nothrow method and check for NULL. Otherwise you'd be using exceptions for control flow, which is not good practice.

    On the other hand, if your program absolutely needs to have that memory allocated successfully in order to be able to function, use try-catch to catch (not necessarily in the immediate vicinity of the new) an exception and exit gracefully from the program.

提交回复
热议问题