C++ 内存分配new (std::nothrow)使用总结

        普通new一个异常的类型std::bad_alloc。这个是标准适应性态。平时一直使用new但是在内存分配失败的时候直接报异常。在内存不足时,new (std::nothrow)并不抛出异常,而是将指针置NULL。std::nothrow可以实现对非零指针的检查。

std::bad_alloc的用法:

       在操作符new 和new [ ]内存分配失败的时候抛出的异常,在分配异常的情况下这时的指针myarray不为NULL;没法用进行Test-for-NULL检查,Test-for-NULL这是个好习惯。

#include      // std::cout
#include           // std::bad_alloc
 
int main()
{
	char *p;
	int i = 0;
	try
	{
		do
		{
			p = new char[1024 * 1024];         //每次1M
			i++;
		} while (p);
	}
	catch(std::exception &e)
	{
		std::cout << e.what() << "\n"
			        << "分配了&#

你可能感兴趣的:(C++入门及项目实战宝典,new,(std::nothrow))