C++ new的nothrow关键字和new_handler用法
new && new(std::nothrow)
new(std::nothrow) 顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样可以方便的通过if(p == NULL) 来判断new操作是否成功
普通的new操作,如果分配内存失败则会抛出异常,虽然后面一般也会写上if(p == NULL) 但是实际上是自欺欺人,因为如果分配成功,p肯定不为NULL;而如果分配失败,则程序会抛出异常,if语句根本执行不到。
因此,建议在c++代码中,凡是涉及到new操作,都采用new(std::nothrow),然后if(p==NULL)的方式进行判断
#include <new> #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; //void __cdecl newhandler() //{ // printf(".....%20s,%10d,,,,,,,\n", __FUNCTION__, __LINE__); // return; //} int main() { // set_new_handler(newhandler); char *p = new char[0x2000000]; if(NULL == p) { //记录日志 printf(".....%20s,%10d,,,,,,,\n", __FUNCTION__, __LINE__); return false; } printf(".....%20s,%10d, p=0x%10x,,,,,,,\n", __FUNCTION__, __LINE__, p); return 0; }
不做任何处理,抛出异常:
[[email protected] nfs] # ./a.out terminate calleda.out/636: potentially unexpected fatal signal 6. after throwing an instance of ‘ Pid: 636, comm: a.out what(): std:CPU: 0 Tainted: P (3.0.8 #1-svn16375) :bad_alloc PC is at 0x40253a98 LR is at 0x40253a44 pc : [<40253a98>] lr : [<40253a44>] psr: 60000010 sp : bef34bb0 ip : 4029615c fp : bef34c6c r10: 008ae1d8 r9 : 00000000 r8 : 401ca704 r7 : 0000010c r6 : 40296394 r5 : 00000006 r4 : 0000027c r3 : 40296144 r2 : 00000006 r1 : 0000027c r0 : 00000000 Flags: nZCv IRQs on FIQs on Mode USER_32 ISA ARM Segment user Control: 0005317f Table: 824bc000 DAC: 00000015 [<c002dd4c>] (show_regs+0x0/0x50) from [<c0055e08>] (get_signal_to_deliver+0x35c/0x384) r4:020c0027 r3:0000000a [<c0055aac>] (get_signal_to_deliver+0x0/0x384) from [<c002eb70>] (do_signal+0x70/0x56c) [<c002eb00>] (do_signal+0x0/0x56c) from [<c002f0c0>] (do_notify_resume+0x54/0x60) [<c002f06c>] (do_notify_resume+0x0/0x60) from [<c002c194>] (work_pending+0x24/0x28) r4:0000027c r3:20000013 Aborted
若设置了set_new_handler,则会进入到死循环
时间: 2024-10-23 20:46:08