operator new中为啥要有无限循环
operator new中为什么要有无限循环
下面是一个non-member operator new的伪代码
不太明白为什么 operator nwe中应该内含一个无穷循环。我知道如果有这个无穷循环存在的话,假如内存分配失败,会无限地调用globalHandler指向的函数。可为什么要这样呢?
------解决思路----------------------
new_handler 是一个处理内存分配失败的函数,它所做的事情最常见的就是释放掉一部分暂时不用的内存,等它完成后刚刚分配失败的应该就可以分配成功了,需要再次去尝试分配内存,所以就有了循环。
------解决思路----------------------
如果要退出循环,只需要把 new handler 设置成 0 就行了
下面是一个non-member operator new的伪代码
void * operator new(std::size_t size) throw(std::bad_alloc)
{ // your operator new might
using namespace std; // take additional params
if (size == 0) { // handle 0-byte requests
size = 1; // by treating them as
} // 1-byte requests
while (true) {
attempt to allocate size bytes;
if (the allocation was successful)
return (a pointer to the memory);
// allocation was unsuccessful; find out what the
// current new-handling function is (see below)
new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);
if (globalHandler) (*globalHandler)();
else throw std::bad_alloc();
}
}
不太明白为什么 operator nwe中应该内含一个无穷循环。我知道如果有这个无穷循环存在的话,假如内存分配失败,会无限地调用globalHandler指向的函数。可为什么要这样呢?
------解决思路----------------------
new_handler 是一个处理内存分配失败的函数,它所做的事情最常见的就是释放掉一部分暂时不用的内存,等它完成后刚刚分配失败的应该就可以分配成功了,需要再次去尝试分配内存,所以就有了循环。
------解决思路----------------------
如果要退出循环,只需要把 new handler 设置成 0 就行了