In the example below, how do you make sure that the first array is deleted when the allocation for the second array fails? (With deliberate mistake of "-3" to cause an exception to be thrown for demonstration purposes).
#include <iostream>
using namespace std;
void func(int n1, int n2)
{
int *array1 = new int[n1];
cout << "alloc 1" << endl;
int *array2 = new int[n2];
cout << "alloc 2" << endl;
// Something useful with these arrays goes here!
delete[] array1;
cout << "deleted 1" << endl;
delete[] array2;
cout << "deleted 2" << endl;
}
int main(int argc, char *argv[])
{
try
{
func(10, -3);
}
catch(bad_alloc ex)
{
cout << "bad alloc" << endl;
}
return 0;
}
Or is "array1" deleted automatically?
Update
I can't use "std::vector" as I'm calling legacy functions, as well as my own functions that both use arrays.
A messy but functional solution:
void func(int n1, int n2)
{
int *array1;
int *array2;
int v = 0;
try
{
array1 = new int[n1];
cout << "alloc 1" << endl;
v = 1;
array2 = new int[n2];
cout << "alloc 2" << endl;
// Something useful with these arrays goes here!
}
catch(bad_alloc ex)
{
cout << "bad alloc func" << endl;
if (v == 1)
{
delete[] array1;
cout << "deleted 1" << endl;
}
throw;
}
delete[] array1;
delete[] array2;
}
int main(int argc, char *argv[])
{
try
{
func(10, -3);
}
catch(bad_alloc ex)
{
cout << "bad alloc main" << endl;
}
return 0;
}