简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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