C++的new与nothrow、new_handler关键字
07 Dec 20121.1 new
#includeint main() { try { int *pInt = new int(); } catch (std::bad_alloc e) { // new申请内存失败时会抛出bad_alloc异常,而malloc不会 } return 0; } </pre> 1.2 nothrow
#include#include int main() { int *pInt = new (std::nothrow)int(); if (pInt == NULL) { std::cout << "申请内存失败"; } return 0; } </pre> 1.3 new_handler
#include#include #include void __cdecl newhandler() { std::cout << "申请内存失败"; exit(0); } int main() { std::set_new_handler(newhandler); int *pInt = new int(); // 如果申请内存失败则调用newhandler()函数。 return 0; } </pre> </section>