当前位置:网站首页>set_new_handler(0)是什么意思?有什么用?
set_new_handler(0)是什么意思?有什么用?
2022-08-11 03:53:00 【林夕07】
出自《STL源码剖析》第45页中有一行代码
set_new_handler(0);
源代码
inline T* _allocate(ptrdiff_t size, T*)
{
std::set_new_handler(0);
T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
if (tmp == 0)
{
std::cerr << "out of menory" << std::endl;
}
return tmp;
}
解释
首先说一下C++对内存分配的原理。如果程序员决定用new operator向计算机申请一块内存,那么就可能会遇到内存不够的情况。一旦内存不够申请失败,那么默认情况下C++会抛出std::bad_alloc异常。但是如果你不想让它抛出异常,而是想自己写一个程序来处理内存不够的情况,那么你就可以用set_new_handler(new_handler),把new_handler指向你写的内存不够的处理程序。这样内存不够了的话C++就会去调用你写的内存不够处理程序,然后再做后续处理。如果你写set_new_handler(0)也就是set_new_handler(nullptr),实际上就是强制C++认为你没有自定义的内存不够处理程序(因为指针是0嘛),所以说当内存不够的时候,C++就会直接抛出std:bad_alloc异常。
因为在这个例子中是一个模板函数,所以说谁也不知道用户在模板实例化的时候前面有没有给set_new_handler指定什么自定义的内存不够处理函数。所以这个用set_new_handler(0),就是为了强制C++在内存不够的时候抛出std:bad_alloc,而不是去执行什么其他自定义的内存不够处理程序。所以这里用set_new_handler(0)不是没有用,而是强制C++在内存不够的时候一定要抛出std:bad_alloc异常
总结
set_new_handler(0)主要是为了卸载目前的内存分配异常处理函数,这样就会导致一旦分配内存失败,C++就会强制性抛出std:bad_alloc异常,而不是跑到处理某个异常处理函数去处理。
边栏推荐
- 【FPGA】day20-I2C读写EEPROM
- 【FPGA】名词缩写
- 【ADI低功耗2k代码】基于ADuCM4050的ADXL363、TMP75的加速度、温度检测及串口打印、蜂鸣器播放音乐(孤勇者)
- CTO said that the number of rows in a MySQL table should not exceed 2000w, why?
- 论文精度 —— 2017 CVPR《High-Resolution Image Inpainting using Multi-Scale Neural Patch Synthesis》
- STC8H development (15): GPIO drive Ci24R1 wireless module
- 常见布局效果实现方案
- Leetcode 669. 修剪二叉搜索树
- 高度塌陷问题的解决办法
- The FTP error code list
猜你喜欢

What is machine learning?Explain machine learning concepts in detail

leetcode刷题第13天二叉树系列之《98 BST及其验证》

DNS separation resolution and intelligent resolution

使用jackson解析json数据详讲

A large horse carries 2 stone of grain, a middle horse carries 1 stone of grain, and two ponies carry one stone of grain. It takes 100 horses to carry 100 stone of grain. How to distribute it?

Qnet弱网测试工具操作指南

机器学习可以应用在哪些场景?机器学习有什么用?

Use jackson to parse json data in detail

Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)

【FPGA】day21- moving average filter
随机推荐
我的 archinstall 使用手册
typedef定义结构体数组类型
C语言 recv()函数、recvfrom()函数、recvmsg()函数
leetcode刷题第13天二叉树系列之《98 BST及其验证》
构建程序化交易系统需要注意什么问题?
云平台下ESB产品开发步骤说明
LeetCode814算题第15天二叉树系列值《814 二叉树剪枝》
2022-08-10 The sixth group Hiding spring study notes
Pinduoduo store business license related issues
AI+医疗:使用神经网络进行医学影像识别分析
音频编解码,利用FAAC来实现AAC编码
How to rebuild after pathman_config and pathman_config_params are deleted?
How can users overcome emotional issues in programmatic trading?
Interchangeable Measurement Techniques - Geometric Errors
2022-08-10 第六小组 瞒春 学习笔记
What has programmatic trading changed?
【FPGA】day18-ds18b20实现温度采集
Audio codec, using FAAC to implement AAC encoding
Which one to choose for mobile map development?
STC8H development (15): GPIO drive Ci24R1 wireless module