首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::set_new_handler

Defined in header <new>

std::new_handler set_new_handler( std::new_handler new_p );

制造new_p新的全局新处理程序函数并返回先前安装的新处理程序。

新处理程序函数是由分配函数每当内存分配尝试失败时。它的目的是三件事之一:

1%29使更多内存可用

2%29终止程序%28例如。打电话std::terminate%29

3%29抛出类型异常std::bad_alloc或衍生自std::bad_alloc...

默认实现抛出std::bad_alloc.用户可以安装自己的新处理程序,这可能提供与默认行为不同的行为。

如果新处理程序返回时,分配函数重复先前失败的分配尝试,并调用新处理程序如果分配再次失败的话。结束循环,新处理程序可能打电话std::set_new_handler(nullptr)*如果在尝试分配失败后,分配函数发现std::get_new_handler返回一个空指针值,它将引发std::bad_alloc...

在程序启动时,新处理程序为空指针。

This function is thread-safe. Every call to std::set_new_handler synchronizes-with (see std::memory_order) the subsequent std::set_new_handler and std::get_new_handler calls.

(since C++11)

参数

new_p

-

pointer to function of type std::new_handler, or null pointer

返回值

以前安装的新处理程序,如果没有安装,则为空指针值。

例外

(none)

(until C++11)

noexcept specification: noexcept

(since C++11)

二次

代码语言:javascript
复制
#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);
    try {
        while (true) {
            new int[100000000ul];
        }
    } catch (const std::bad_alloc& e) {
        std::cout << e.what() << '\n';
    }
}

二次

产出:

二次

代码语言:javascript
复制
Memory allocation failed, terminating
std::bad_alloc

二次

另见

operator newoperator new[]

allocation functions (function)

get_new_handler (C++11)

obtains the current new handler (function)

new_handler

function pointer type of the new handler (typedef)

bad_alloc

exception thrown when memory allocation fails (class)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券