C++ 类提供 RAII 习惯用法。因此,您不必关心异常:
void function()
{
// The memory will be freed automatically on function exit
std::vector<int> vector(1000);
// Do some work
}
但是,如果您(出于某些原因)使用某些纯 C API,则必须围绕它创建 C++ 包装器或使用 try/catch 块
void function()
{
int *arr = (int*)malloc(1000*sizeof(int));
if (!arr) { throw "cannot malloc"; }
try
{
// Do some work
}
catch (...)
{
free(arr); // Free memory in case of exception
throw; // Rethrow the exception
}
// Free memory in case of success
free(arr);
}
即使您使用带有 RAII 习惯用法的 C++ 类,有时您也必须编写具有强大异常安全保证的代码:
void function(std::vector<const char*> &vector)
{
vector.push_back("hello");
try
{
// Do some work
vector.push_back("world");
try
{
// Do other work
}
catch (...)
{
vector.pop_back(); // Undo vector.push_back("world")
throw; // Rethrow the exception
}
}
catch (...)
{
vector.pop_back(); // Undo vector.push_back("hello");
throw; // Rethrow the exception
}
}
但是这些结构非常笨重。
有没有办法强制在函数退出时运行一些清理代码?类似于atexit
,但在函数范围内的东西......
有没有办法在不使用嵌套的 try/catch 块的情况下运行一些回滚代码?
我想要一些像这样工作的运算符或函数:
void function(std::vector<const char*> &vector)
{
int *arr = malloc(1000*sizeof(int));
onexit { free(arr); }
vector.push_back("hello");
onexception { vector.pop_back(); }
// Do some work
vector.push_back("world");
onexception { vector.pop_back(); }
// Do other work
}
如果可以创建这样的功能,是否有任何理由避免使用它们?其他编程语言中是否有这样的结构?