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#include #include #include 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;}
不做任何处理,抛出异常:
[root@dvrdvs 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_allocPC is at 0x40253a98LR is at 0x40253a44pc : [<40253a98>] lr : [<40253a44>] psr: 60000010sp : bef34bb0 ip : 4029615c fp : bef34c6cr10: 008ae1d8 r9 : 00000000 r8 : 401ca704r7 : 0000010c r6 : 40296394 r5 : 00000006 r4 : 0000027cr3 : 40296144 r2 : 00000006 r1 : 0000027c r0 : 00000000Flags: nZCv IRQs on FIQs on Mode USER_32 ISA ARM Segment userControl: 0005317f Table: 824bc000 DAC: 00000015[] (show_regs+0x0/0x50) from [ ] (get_signal_to_deliver+0x35c/0x384) r4:020c0027 r3:0000000a[ ] (get_signal_to_deliver+0x0/0x384) from [ ] (do_signal+0x70/0x56c)[ ] (do_signal+0x0/0x56c) from [ ] (do_notify_resume+0x54/0x60)[ ] (do_notify_resume+0x0/0x60) from [ ] (work_pending+0x24/0x28) r4:0000027c r3:20000013Aborted
若设置了set_new_handler,则会进入到死循环