gpt4 book ai didi

c++ - C++ 中的 operator new、new_handler 函数

转载 作者:太空狗 更新时间:2023-10-29 20:03:29 25 4
gpt4 key购买 nike

这是 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 异常或返回空指针和 else 主体工作,抛出 bad_alloc 异常。我的问题是为什么 new_handler 函数有时会抛出异常,如果它可以返回空指针,否则 body 会这样做?

最佳答案

1) Why first time 0 is passed as parametr to set_new_handler function?

根据 docs这段代码:

new_handler globalHandler = set_new_handler(0);
set_new_handler(globalHandler);

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

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

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

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

when allocation failed, new_handler function invoked, try to allocate momory

未知。我看不到它在这里分配任何内存的位置,因为没有代码。用户可以在新处理程序中自由执行任何操作,但分配内存是我最不想做的事情。事实上,适当的行为是释放一些内存。

and if and only if cant makes more memory, it return pointer to the start of allocated memory or if it cant, it throws bad_alloc exeption or returns null pointer

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

typedef void (*new_handler)();

and else body works, which throws a bad_alloc exeption

else block 仅在没有安装处理程序(它是空指针)时才有效,而不是在 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?

关于c++ - C++ 中的 operator new、new_handler 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com