使用带nothrow的new,如果分配失败,那么会返回一个空指针;C++不同版本之间对于new操作的实现是不尽相同的,
如,一些版本在失败时,即使使用的是不带nothrow选项的new,也会返回空地址。
1、没有try catch和new(nothrow)
#include <iostream>
#include <new> //new ,bad_alloc
using namespace std;
int main( )
{
const int ARRAY_NUMS=10;
cout<<"how large should be the array?/n";
int capacity=0;
cin>>capacity;
double* array[ ARRAY_NUMS ];
for( int i=0;i<ARRAY_NUMS;++i )
{
array[ i ]=new double[ capacity ];
cout<<"allocate "<<capacity<<" doubles for i= "<<i<<endl;
}
cout<<"All arrays is allocated completed/n";
for( int i=0;i<ARRAY_NUMS;++i )
delete [ ] array[ i ];
cout<<"delete over/n";
return 0;
}
当我们输入1000000000,时的结果:
myyangcui@myyangcui:~/Mypro/my_files$ ./testcpp
how large should be the array?
10000000000
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
myyangcui@myyangcui:~/Mypro/my_files$
2、使用try catch
#include <iostream>
#include <new> //new ,bad_alloc
using namespace std;
int main( )
{
const int ARRAY_NUMS=10;
cout<<"how large should be the array?/n";
int capacity=0;
cin>>capacity;
int i;
double* array[ ARRAY_NUMS ];
try
{
for( i=0;i<ARRAY_NUMS;++i )
{
array[ i ]=new double[ capacity ];
cout<<"allocate "<<capacity<<" doubles for i= "<<i<<endl;
}
}
catch( bad_alloc ex )
{
cout<<"/nException:"<<ex.what( )<<" for i="<<i<<endl;
exit( -1 );
}
cout<<"All arrays is allocated completed/n";
for( int i=0;i<ARRAY_NUMS;++i )
delete [ ] array[ i ];
cout<<"delete over/n";
return 0;
}
我们的结果是:
myyangcui@myyangcui:~/Mypro/my_files$ ./testcpp
how large should be the array?
10000000000
Exception:std::bad_alloc for i=0
myyangcui@myyangcui:~/Mypro/my_files$
3、使用new(nothrow) Type []
#include <iostream>
#include <new> //new ,bad_alloc
#include <cstdlib>
using namespace std;
int main( )
{
const int ARRAY_NUMS=10;
cout<<"how large should be the array?/n";
int capacity=0;
cin>>capacity;
int i;
double* array[ ARRAY_NUMS ];
for( i=0;i<ARRAY_NUMS;++i )
{
array[ i ]=new( nothrow ) double[ capacity ];
if( array[ i ] ==NULL)
{
cout<<"Allocate failed for i= "<<i<<endl;
exit( -1 );
}
cout<<"allocate "<<capacity<<" doubles for i= "<<i<<endl;
}
cout<<"All arrays is allocated completed/n";
for( int i=0;i<ARRAY_NUMS;++i )
delete [ ] array[ i ];
cout<<"delete over/n";
return 0;
}
结果:
myyangcui@myyangcui:~/Mypro/my_files$ ./testcpp
how large should be the array?
100000000000
Allocate failed for i= 0
myyangcui@myyangcui:~/Mypro/my_files$