这是new运算符的伪代码:
while (true)
{
Attempt to allocate size bytes
if (the allocation was successful)
return (a pointer to the memory);
// The allocation was unsuccessful; find out what the
// current new-handling function is
new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);
if (globalHandler)
(*globalHandler)();
else
throw std::bad_alloc();
}
问题 :
1)为什么第一次将0作为参数传递给set_new_handler函数?
2)它说,当分配失败时,将调用new_handler函数,尝试分配内存,并且当且仅当不能增加内存时,它才将指针返回到已分配内存的开头,或者如果不能,则抛出bad_alloc异常或返回空指针,否则 body 会起作用,这会抛出bad_alloc异常。
我的问题是,为什么new_handler函数有时会抛出异常,如果它可以返回null指针,否则body会这样做呢?
最佳答案
根据docs这个代码:
new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);
将要
(1)将处理程序设置为空指针(作为参数传递)
(2)将指向当前处理程序的函数指针检索到
globalHandler
变量中(3)将处理程序设置回原来的状态(无论globalHandler指向什么)
执行此操作是为了检索指向当前处理程序的函数指针。
未知。我看不到它在哪里分配任何内存,因为没有代码。用户可以在新处理程序内自由执行任何操作,但是分配内存是我要做的最后一件事。实际上,适当的行为将是释放一些内存。
错误的。
new_handler
不返回任何内容,它是指向不接受任何参数并返回typedef
的函数指针的void
:typedef void (*new_handler)();
else
块仅在未安装处理程序(它为空指针)时起作用,而在new_handler
“失败”或引发异常或其他情况时不起作用像这样阅读:
void* operator new (std::size_t size, optional blah blah here) blah blah here
{
while(true) // until universe exists (or a nearest power station)
{
// Try to allocate somehow
// Allocation failed
// Retrieved `global_handler` - a pointer to `void (*new_handler)` somehow
if (globalHandler) // global_handler is not null pointer?
{
(*globalHandler)(); // no, invoke it and loop again
}
else
{
throw std::bad_alloc(); // it's null, nothing to do, exception, sorry
}
}
}
也可以看看:
How should I write ISO C++ Standard conformant custom new and delete operators?