我在一个函数中分配了多个资源,因此有很多指针,我必须从中返回一个指针(比如 ret_ptr)并在离开函数之前释放其他指针(所有 othr_ptr)。
我在这个函数中有多个导出点(其中 ret_ptr 为 0 或指向有效内存或异常)。因此,在所有返回语句之前和异常(catch block )中,我必须删除 othr_ptrs(在函数中执行多次)。 “ScopeGuards”有什么方法可以减少多次清理吗?
X* func()
{
try
{
A* a = new ..;
B* b = new ..;
if (something)
{
delete a;
delete b;
return 0; // return NULL ptr
}
X* x = new ..;
}
catch(...)
{
delete a;
delete b;
return x;
}
delete a;
delete b;
return x;
}
最佳答案
你可以使用 std::unique_ptr
(C++11),你的例子变成这样:
std::unique_ptr<X> func()
{
std::unique_ptr<X> x;
try
{
std::unique_ptr<A> a(new A);
std::unique_ptr<B> b(new B);
if (something)
{
return nullptr;
}
x.reset(new X);
}
catch (...)
{
return std::move(x);
}
return std::move(x);
}
关于c++ - ScopeGuard 在一个函数中使用多个资源分配和退出点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24509973/