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

前端 未结 18 1825
隐瞒了意图╮
隐瞒了意图╮ 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:17

    Yes, new can and will throw if allocation fails. This can happen if you run out of memory or you try to allocate a block of memory too large.

    You can catch the std::bad_alloc exception and handle it appropriately. Sometimes this makes sense, other times (read: most of the time) it doesn't. If, for example, you were trying to allocate a huge buffer but could work with less space, you could try allocating successively smaller blocks.

提交回复
热议问题