set_new_handler例子
2018-01-15 11:12
344 查看
#include <iostream>
/// buffer to be allocated after custom new handler has been installed
char* g_pSafetyBuffer = NULL;
/// exceptional one time release of a global reserve
void my_new_handler()
{
if (g_pSafetyBuffer) {
delete [] g_pSafetyBuffer;
g_pSafetyBuffer = NULL;
std::cout << "[Free some pre-allocated memory]";
return;
}
std::cout << "[No memory to free, throw bad_alloc]";
throw std::bad_alloc();
}
/// illustrates how a custom new handler may work
int main()
{
enum { MEM_CHUNK_SIZE = 1000*1000 }; // adjust according to your system
std::set_new_handler(my_new_handler);
g_pSafetyBuffer = new char[801*MEM_CHUNK_SIZE];
try {
while (true) {
std::cout << "Trying another new... ";
new char[200*MEM_CHUNK_SIZE];
std::cout << " ...succeeded.\n";
}
} catch (const std::bad_alloc& e) {
std::cout << " ...failed.\n";
}
return 0;
}
/// buffer to be allocated after custom new handler has been installed
char* g_pSafetyBuffer = NULL;
/// exceptional one time release of a global reserve
void my_new_handler()
{
if (g_pSafetyBuffer) {
delete [] g_pSafetyBuffer;
g_pSafetyBuffer = NULL;
std::cout << "[Free some pre-allocated memory]";
return;
}
std::cout << "[No memory to free, throw bad_alloc]";
throw std::bad_alloc();
}
/// illustrates how a custom new handler may work
int main()
{
enum { MEM_CHUNK_SIZE = 1000*1000 }; // adjust according to your system
std::set_new_handler(my_new_handler);
g_pSafetyBuffer = new char[801*MEM_CHUNK_SIZE];
try {
while (true) {
std::cout << "Trying another new... ";
new char[200*MEM_CHUNK_SIZE];
std::cout << " ...succeeded.\n";
}
} catch (const std::bad_alloc& e) {
std::cout << " ...failed.\n";
}
return 0;
}
相关文章推荐
- set_new_handler
- C++中的set_new_handler和new_handler 【未完待续】
- 关于set_new_handler
- 关于set_new_handler(转载)
- 关于在vc6.0中使用set_new_handler的问题
- c++中的set_new_handler和new_handler
- C++程序内存分配中set_new_handler…
- c++中的set_new_handler和new_handler
- shining cento in book reading: handle out of memory problem for new operator -by register a global SetNewHandler
- typedef 与 set_new_handler的几种写法
- 关于set_new_handler
- set_new_handler
- std::set_new_handler
- c++中的set_new_handler和new_handler
- 内存分配失败捕捉 set_new_handler
- C++程序内存分配中set_new_handler…
- c++中的set_new_handler和new_handler
- 关于_set_new_handler
- set_new_handler
- 【译】set_new_handler