对于我的生活,我无法弄清楚为什么 nothrow 不起作用。我尝试过不同的标题。还交换了新的和内存头,但输出仍然相同:
0x61ff50 6422400
How many numbers would you like to type: 1000000000
terminate called after throwing an instance of 'std::bad_array_new_length'
what(): std::bad_array_new_length
关于我做错了什么的任何想法?我正在寻找一种方法来避免程序崩溃并使用任意值作为数组大小。似乎我必须使用最大大小内的数组,这将为程序带来稳定性,因此我无法测试 nothrow 对象;留给我使用异常的唯一选择。
#include <iostream>
#include <memory>
#include <new> // also either/or this
using namespace std ;
int main ()
{
int i, n ;
int *p ;
cout << p << " " << *p << endl ;
cout << "How many numbers would you like to type: " ;
cin >> i ;
p = new (nothrow) int[i] ;
if (!p)
{
cout << "Error: memory could not be allocated" ;
}
else
{
for (n = 0 ; n < i ; n ++)
{
cout << "Enter number: " ;
cin >> p[n] ;
}
cout << endl << p << endl << *p << endl ;
cout << "You have entered: " ;
for (n = 0 ; n < i ; n++ )
cout << p[n] << ", " ;
delete[] p ;
cout << endl << p << " " << *(p + 0) << endl ;
p = nullptr ;
cout << endl << p << endl ;
p = &i ;
cout << endl << p << " " << *p ;
}
cin.get() ;
return 0 ;
}