什么可以“new_handler”除了垃圾收集之外,在C ++中使用吗? [英] What can "new_handler" be used for in C++ besides garbage collection?

查看:145
本文介绍了什么可以“new_handler”除了垃圾收集之外,在C ++中使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++程序可以定义和设置一个 new_handler(),该内存分配函数应该从 operator new()

C++ programs can define and set a new_handler() that should be called from memory allocation functions like operator new() if it's impossible to allocate memory requested.

自定义 new_handler()的一个用法是处理不会在分配失败时抛出异常的C ++实现。另一个用途是在实现垃圾收集的系统上启动垃圾收集。

One use of a custom new_handler() is dealing with C++ implementations that don't throw an exception on allocation failure. Another use is initiating garbage collection on systems that implement garbage collection.

自定义 new_handler()

推荐答案

类似于垃圾收集应用程序,您可以使用新处理程序释放任何缓存数据可能会保留。

In a similar vein to the garbage collection application, you can use the new handler to free up any cached data you may be keeping.

假设您正在缓存从磁盘读取的某些资源数据或某些计算的中间结果。这是您可以在任何时候重新创建的数据,因此当新的处理程序被调用(意味着您已经用尽了堆),您可以释放缓存数据的内存,然后从新处理程序返回。希望 new 现在能够进行分配。

Say that you're caching some resource data read from disk or the intermediate results of some calculation. This is data that you can recreate at any time, so when the new handler gets called (signifying that you've run out of heap), you can free the memory for the cached data, then return from the new handler. Hopefully, new will now be able to make the allocation.

在许多情况下,虚拟内存可以目的:如果你有足够的虚拟地址空间,你可以简单地让你的缓存数据被交换到磁盘。在32位系统上,这不是真的了,所以新的处理程序是一个有趣的选择。许多嵌入式系统将面临类似的限制。

In many cases, virtual memory can serve the same purpose: You can simply let your cached data get swapped out to disk -- if you've got enough virtual address space. On 32-bit systems, this isn't really the case any more, so the new handler is an interesting option. Many embedded systems will face similar constraints.

这篇关于什么可以“new_handler”除了垃圾收集之外,在C ++中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆