平时一直使用new但是在内存分配失败的时候直接报异常,怎么处理后边听其他人讨论时知道了std::nothrow.
这个面试的时候写上绝对是亮点,实现对非零指针的检查。
最近才发现http://www.cplusplus.com是个好东西。
1.std::bad_alloc
在操作符new 和new [ ]内存分配失败的时候抛出的异常,在分配异常的情况下这时的指针myarray不为NULL;
没法用进行Test-for-NULL检查,同时记住Test-for-NULL这是个好习惯。
#include <iostream> // std::cout
#include <new> // 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"
<< "分配了" << i << "M" << std::endl;
};
//x86 :
// bad allocation
// 分配了1893M
long num = 0x7fffffff; //0x7fffffff = 2,147,483,647 = 2047*1024*1024 = 2047M
char* myarray = nullptr;
try
{
//vs2015 x86 error C2148: 数组的总大小不得超过 0x7fffffff 字节
myarray = new char[2047 * 1024 * 1024]; ///1024 * 1024 * 1024
}
catch (std::bad_alloc &ba)
{
std::cerr<< "bad_alloc caught: " << ba.what() << '\n'; //bad_alloc caught: bad allocation
}
delete[] myarray;
return 0;
}
2.std::nothrow
"new(std::nothrow)"在分配内存失败时会返回一个空指针。而不是触发std::bad_alloc,可以方便的进行Test-for-NULL检查。
bad_alloc example
#include <iostream> // std::cout
#include <new> // std::bad_alloc
int main()
{
char *p= NULL;
int i = 0;
do
{
p = new (std::nothrow) char[1024 * 1024]; //每次1M
i++;
} while (p);
if (NULL == p)
{
std::cout << "分配了 " << i - 1 << " M内存" //分配了 1890 Mn内存第 1891 次内存分配失败
<< "第 " << i << " 次内存分配失败";
}
long num = 0x7fffffff; //0x7fffffff = 2,147,483,647 = 2047*1024*1024 = 2047M
char* myarray = nullptr;
//vs2015 x86 error C2148: 数组的总大小不得超过 0x7fffffff 字节
myarray = new (std::nothrow)char[2047 * 1024 * 1024]; ///1024 * 1024 * 1024
if (nullptr == myarray)
{
std::cerr << " new (std::nothrow)char[2047 * 1024 * 1024] 内存分配失败" << std::endl;
}
else
{
std::cout<<" new (std::nothrow)char[2047 * 1024 * 1024] 内存分配成功" << std::endl;
}
return 0;
}