2

Whenever we use set_new_handler (std::new_handler handle_mem_alloc) for handling memory allocation failures and if any memory allocation failure happens then handle_mem_alloc () will be called. If we are not throwing any exception from inside this function the new operator will not throw any error.

My question is, does constructor gets called in this scenario when there is mem allocation failure and we are not throwing any exception from handle_mem_alloc() function?

4

1 回答 1

4

从此参考中,新的处理程序必须执行以下操作之一:

  1. 提供更多可用内存
  2. 终止程序(例如通过调用 std::terminate)
  3. 抛出 std::bad_alloc 类型的异常或从 std::bad_alloc 派生的异常。

如果新处理程序返回,则再次尝试分配,如果仍然失败,则再次调用新处理程序(未缓存,并且可能被新处理程序更改),依此类推。

所以你的问题的答案是否定的,在内存分配实际成功之前永远不会调用构造函数。

于 2013-10-02T10:40:39.103 回答