简体   繁体   English

C ++中的forsee std :: bad_alloc

[英]forsee std::bad_alloc in C++

As far as I understand std::bad_alloc exceptions in C++ are triggered when the program runs out of memory. 据我所知,当程序内存不足时,会触发C ++中的std :: bad_alloc异常。 Is there a way to monitor how much memory left there are and trigger a special routine before we reach the point of no return ? 有没有办法监控剩余的内存量,并在我们到达不归路之前触发特殊程序?

No, but you can register a handler with std::set_new_handler , which the default implementation of the global operator new() executes in a loop until either the handler doesn't return or there is no further handler registered. 不,但是你可以用std::set_new_handler注册一个处理程序,全局operator new()的默认实现在循环中执行,直到处理程序没有返回或者没有注册进一步的处理程序。 The handler may itself try to free up some more memory, or post a log message, or something similar. 处理程序本身可能会尝试释放更多内存,或发布日志消息或类似内容。

The specifics of how much memory are available for your allocation function depend very heavily on your platform and your operating system, though, so don't expect too much. 但是,分配功能可用内存的具体细节在很大程度上取决于您的平台和操作系统,所以不要期望太多。

For example, on systems that oversubscribe memory, your allocations may succeed, but your program could still die because the system is out of memory. 例如,在超额预订内存的系统上,您的分配可能会成功,但您的程序仍可能因为系统内存不足而死亡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM