【C++】std::set_new_handler使用场景

std::set_new_handler使用场景

C++的STL提供了std::set_new_handler,new操作分配内存失败时,会先调用这个Handler。
默认的new_handler行为是,抛出std::bad_alloc异常。

std::new_handler原型:

// (until C++11)
std::new_handler set_new_handler( std::new_handler new_p ) throw();
// (since C++11)
std::new_handler set_new_handler( std::new_handler new_p ) noexcept;

cppreference官网中对其说明如下

The new-handler function is the function called by allocation
functions whenever a memory allocation attempt fails. Its intended
purpose is one of three things:

  1. make more memory available,
  2. terminate the program (e.g. by calling std::terminate)
  3. throw exception of type std::bad_alloc or derived from std::bad_alloc.

The default implementation throws
std::bad_alloc. The user can install their own new-handler, which may
offer behavior different than the default one.

allocation function 重复尝试分配内存,每次失败的时候都会调用new-handler,直到new-handler中调用了std::set_new_handler(nullptr),然后会抛出 std::bad_alloc异常。

If new-handler returns, the allocation function repeats the
previously-failed allocation attempt and calls the new-handler again
if the allocation fails again. To end the loop, new-handler may call
std::set_new_handler(nullptr): if, after a failed allocation attempt,
allocation function finds that std::get_new_handler returns a null
pointer value, it will throw std::bad_alloc.

  • 小例
#include <iostream>
#include <new>
 
void handler()
{
    std::cout << "Memory allocation failed, terminating\n";
    std::set_new_handler(nullptr);
}
 
int main()
{
    std::set_new_handler(handler);

    while (true)
    {
        new int[1000'000'000ul]();
    }

}

使用场景

  • 记录异常事件:通过std::set_new_handler设置内存不足时的new-handler,当检测到内存异常时,通过日志系统进行记录(PS:此时需要考虑日志系统是否可用)

  • 预先分配一段内存并在异常时释放内存尝试自救:运行初期,事先分配一段内存池。当内存不足new失败时,释放这段内存进行自救(保证系统可最低限度的运行正常)。同时,通知系统异常消息,让用户进行重启、Reset等操作。

  • 设计LowMemory:系统低内存时,进程自救策略。比如Kill掉一些不重要的进程,主动关闭系统某些功能

实际上,Linux、Android等系统,都有其完善的内存策略,如交换分区、LowMemeory Killer、Kenerl Panic等等。并且实际开发时,会有完善的流程(设计、review),很少出现单纯因为某些程序重复new导致内存不足,而触发new-handler。
因为在触发之前,常规系统的lowmemory killer已经把异常进程kill掉了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值