小编Sen*_*yan的帖子

理解new-handler的行为

我正在阅读Scott Meyers的Effective C++ 55,并从第49项中得到一个问题:

operator new无法满足内存请求时,它会重复调用new-handler函数,直到找到足够的内存.

精心设计的newhandler函数必须执行以下操作之一:

  • 提供更多内存.
  • 安装不同的新处理程序.
  • 卸载新处理程序
  • 抛出一个例外
  • 不归路

new无法分配内存时,就意味着没有足够的内存,问题是newhandler如何以及从哪里分配更多内存?

你能解释所有这些步骤吗?

c++ new-operator dynamic-memory-allocation

17
推荐指数
2
解决办法
801
查看次数

c ++中的operator new,new_handler函数

这是运营商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会这样做?

c++ memory memory-management new-operator

3
推荐指数
1
解决办法
1111
查看次数