c ++中的operator new,new_handler函数

Sen*_*yan 3 c++ memory memory-management new-operator

这是运营商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();
  }
Run Code Online (Sandbox Code Playgroud)

问题:

1)为什么第一次将0作为参数传递给set_new_handler函数?

2)它表示当分配失败时,调用new_handler函数,尝试分配momory,当且仅当不能产生更多内存时,它返回指向已分配内存的开始的指针,或者如果它不能,则抛出bad_alloc exeption或返回空指针并且else body工作,抛出bad_alloc exeption.我的问题是为什么new_handler函数有时抛出exeption,如果它可以返回空指针,否则body会这样做?

Iva*_*rop 5

1)为什么第一次将0作为参数传递给set_new_handler函数?

根据文档这段代码:

new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);
Run Code Online (Sandbox Code Playgroud)

(1)设置处理程序为空指针(作为参数传递)

(2)将当前处理程序的函数指针检索到globalHandler变量中

(3)将处理程序设置回原来的状态(无论globalHandler现在指向什么)

执行此操作以检索指向当前处理程序的函数指针.

当分配失败时,调用new_handler函数,尝试分配momory

未知.我没有看到它在哪里分配任何内存,因为它没有代码.用户可以在新处理程序内自由执行任何操作,但分配内存是我要做的最后一件事.事实上,适当的行为是释放一些记忆.

并且当且仅当不能产生更多内存时,它返回指向已分配内存开始的指针,或者如果它不能,则抛出bad_alloc exeption或返回空指针

错误.new_handler不返回任何内容,它是typedef一个函数指针,不接受任何参数并返回void:

typedef void (*new_handler)();
Run Code Online (Sandbox Code Playgroud)

和body工作,抛出bad_alloc exeption

elseblock仅在没有安装处理程序时运行(它是空指针),而不是在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
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅: 如何编写符合ISO C++标准的自定义新建和删除运算符?