在下面的示例中,如何确保在第二个数组的分配失败时删除第一个数组?(故意犯"-3“错误,导致为演示目的抛出异常)。
#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;
}或者"array1“是自动删除的?
更新
我不能使用"std::vector“,因为我调用的是遗留函数,以及我自己使用数组的函数。
一个混乱但功能强大的解决方案
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;
}发布于 2019-08-10 19:14:09
使用std::vector。它将自动释放内存资源。
您可以使用数据()成员函数访问底层指针,以便将数据传递给遗留函数。
发布于 2019-08-10 19:24:02
您可以将第二个分配放在try…中。渔获物块:
void func(int n1, int n2)
{
int* array1 = new int[n1];
cout << "alloc 1" << endl;
int* array2;
try {
array2 = new int[n2];
}
catch (bad_alloc ex) {
delete[] array1;
throw;
}
cout << "alloc 2" << endl;
// Something useful with these arrays goes here!
delete[] array1;
cout << "deleted 1" << endl;
delete[] array2;
cout << "deleted 2" << endl;
return;
}然后,您可以在重新抛出异常之前清理第一个(成功)分配,以便您的调用函数捕获!
https://stackoverflow.com/questions/57444988
复制相似问题