C++new实现机制
1.new和delete最终调用malloc和free
2.new操作数据类型两种:
2.1基本数据类型
int *p=new int;
00E8139E push 4
00E813A0 call operator new (0E81172h)
00E813A5 add esp,4
00E813A8 mov dword ptr [ebp-0D4h],eax
00E813AE mov eax,dword ptr [ebp-0D4h]
00E813B4 mov dword ptr [p],eax
00E813A0 call operator new (0E81172h)
00E813A5 add esp,4
00E813A8 mov dword ptr [ebp-0D4h],eax
00E813AE mov eax,dword ptr [ebp-0D4h]
00E813B4 mov dword ptr [p],eax
传入4个字节参数,然后调用operetor new重载函数(new操作符重载看下)
void *__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);
}
{ // 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);
}
调用malloc失败后,会调用_callnewh函数,如果该函数的返回值为0,则抛出异常(下节说下new失败的处理)
注意:new分配内存失败后,会抛出异常,bad_alloc对象,而不是指针为NULL
这个_callnewh是什么呢?它是一个new handler,通俗来讲就是new失败的时候调用的回调函数。可以通过_set_new_handler来设置。下面举个实例:
- #include <stdio.h>
- #include <new.h>
- int MyNewHandler(size_t size)
- {
- printf("Allocation failed.Try again");
- return 1; //continue to allocate
- //return 0; //stop allocating,throw bad_alloc
- }
- void main()
- {
- // Set the failure handler for new to be MyNewHandler.
- _set_new_handler(MyNewHandler);
- while (1)
- {
- int* p = new int[10000000];
- }
- }
先根据类似简单类型给对象分配内存空间,然后在分配的内存上再调用构造函数初始化对象