我的一个类变量是2D数组。 大小取决于用户输入。 用户可以输入可能超过其硬件限制的大小。 所以我想妥善处理这个问题。 以下代码是否正确?
int counter;
try
{
int size = 20000;//this is actually from user input
array = new double*[size];
for(counter = 0; counter < size; counter++)
array[counter] = new double[size];
}
catch(std::bad_alloc)
{
try
{
for(int i = 0; i < counter; i++)
delete[] array([i]);
delete[] array;
array = NULL;
//display limitation message
size = 2;
array = new double*[size];
for(int i = 0; i < size; i++)
array[i] = new double[size];
}
//catch again & exit application
}
答案 0 :(得分:1)
你最好的选择是:
std::vector<std::vector<double>> array(size, std::vector<double>(size));
但如果你必须手动完成,那么:
void init_array(int size)
{
int counter;
try
{
array = new double*[size];
// Don't shadow counter here.
for(counter = 0; counter < size; counter++)
{
array[counter] = new double[size];
}
}
catch(std::bad_alloc)
{
// delete in reverse order to mimic other containers.
for(--counter; counter >= 0;--counter)
{
delete[] array[counter];
}
delete[] array;
// retry the call with a smaller size.
// A loop would also work. Depending on context.
// Don't nest another try{} catch block. because your code will
// just get convoluted.
init_array(size/2);
}