Can the C++ `new` operator ever throw an exception in real life?

前端 未结 18 1838
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 08:40

Can the new operator throw an exception in real life?

And if so, do I have any options for handling such an exception apart from killing my application?

18条回答
  •  星月不相逢
    2021-01-30 09:11

    It depends on the compiler/runtime and on the operator new that you are using (e.g. certain versions of Visual Studio will not throw out of the box, but would rather return a NULL pointer a la malloc instead.)

    You can always catch a std::bad_alloc exception, or explicitly use nothrow new to return NULL instead of throwing. (Also see past StackOverflow posts revolving around the subject.)

    Note that operator new, like malloc, will fail when you have run out of memory, out of address space (e.g. 2-3GB in a 32-bit process depending on the OS), out of quota (ulimit was already mentioned) or out of contiguous address space (e.g. fragmented heap.)

提交回复
热议问题