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

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

    From a pure performance perspective it matters little. There is inherent overhead with exception handling, though this overhead is generally worth the trade off in application readability and maintenance. Memory allocation failures of this nature should not be in the 99% case of your application, so this should happen infrequently.

    From a performance perspective you generally want to avoid the standard allocator due to its relatively poor performance anyway.

    All this said, I generally accept the exception throwing version because generally our applications are in a state where if memory allocation fails, there is little we can do other than exit gracefully with an appropriate error message, and we save performance by not requiring NULL checking on our newly allocated resources because by definition an allocation failure will move the scope out from where that matters.

提交回复
热议问题