首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

VC编程,什么时候会调用到不抛错误的默认operator new

2012-06-05 
VC编程,什么时候会调用到不抛异常的默认operator new?我们代码里面的new operator调用的是抛出异常的opera

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>的内容是这样的:

C/C++ code
#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);        }



[解决办法]
申请内存时 用 new(std::nothrow) ClassName; 这样只需要判断 new 的返回值是否为NULL来判断内存是否分配失败

热点排行