1.使用set_new_handler
void nomemery()
{
std::cerr << "unable memery" << std::endl;
}
std::set_new_handler(nomemery);
注意:std和<new.h>文件中都含有set_new_handler函数。测试中发现两set_new_handler都重写或者只重写其中一个都可以解决问题。
个人见解:使用std::set_new_handler
2.使用std::nothrow
while (true)
{
char *p = new char[1000000000];
if (nullptr == p)
{
std::cout << 1 << std::endl;
}
else
{
std::cout << 2 << std::endl;
}
Sleep(500);
}
个人见解:不建议使用。
3.使用try...catch
while (true)
{
char *p = nullptr;
try
{
p = new char[1000000000];
}
catch (const std::exception&)
{
std::cout << "unable memery" << std::endl;
}
if (nullptr == p)
{
std::cout << 1 << std::endl;
}
else
{
std::cout << 2 << std::endl;
}
Sleep(500);
}