set_new_handler用法

来源:互联网 发布:知彼网络科技有限公司 编辑:程序博客网 时间:2024/05/15 14:52

分配内存时,如果每次new出来 ,都要判断是否成功(地址是否为空),比较繁琐。
c++提供set_new_handler,当new失败时,会调用set_new_handler设置的回调函数。
new_handler is a function pointer type taking no arguments and returning no value.


实例:

#include <iostream>#include <cstdlib>#include <new>using namespace std;void no_memory(){    cout << "分配内存失败\n" << endl;    exit(1);}int main(){    set_new_handler(no_memory);    cout << "分配1G内存\n" << endl;    char* p = new char[1024 * 1024 * 1024];    cout << "分配成功~\n" << endl;    delete[] p;    return 0;}//可能输出(内存足够大时):/*分配1G内存分配成功~*/
0 0
原创粉丝点击