VC编程,什么时候会调用到不抛异常的默认operator new?
我们代码里面的new operator调用的是抛出异常的operator new.
在vc10下面调试release版的代码,"int *pi=new int;"这句话会调入new.cpp文件里面的
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
我发现这个文件里面有两个operator new(size_t size),一个是抛出异常的版本,一个是不抛出异常的版本。
用一个宏来控制。
问题是,什么时候我们自己写的代码才会调用到没有抛出异常的这个版本呢?
<new>的内容是这样的:
#ifdef _SYSCRT#include <cruntime.h>#include <crtdbg.h>#include <malloc.h>#include <new.h>#include <stdlib.h>#include <winheap.h>#include <rtcsup.h>#include <internal.h>void * operator new( size_t cb ){ void *res; for (;;) { // allocate memory block res = _heap_alloc(cb); // if successful allocation, return pointer to memory if (res) break; // call installed new handler if (!_callnewh(cb)) break; // new handler was successful -- try to allocate again } RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0)); return res;}#else /* _SYSCRT */#include <cstdlib>#include <new>_C_LIB_DECLint __cdecl _callnewh(size_t size) _THROW1(_STD bad_alloc);_END_C_LIB_DECLvoid *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc) { // try to allocate size bytes void *p; while ((p = malloc(size)) == 0) if (_callnewh(size) == 0) { // report no memory static const std::bad_alloc nomem; _RAISE(nomem); } return (p); }