- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
假设我正在做一些在抛出异常时需要清理的事情。
比如我正在创建一个动态数组,我需要构造对象,但是它们的构造函数可能会抛出异常:
size_t const n = 100;
T *const p = static_cast<T *>(operator new(sizeof(T) * n));
size_t i;
for (i = 0; i < n; ++i)
new (&p[i]) T(1, 2, 3); // Not exception-safe if T::T(T const &) throws!
我可以通过 catch (...) { ...; 修复它扔;
:
size_t const n = 100;
T *const p = static_cast<T *>(operator new(sizeof(T) * n));
size_t i;
try
{
for (i = 0; i < n; ++i)
new (&p[i]) T(1, 2, 3);
}
catch (...)
{
while (i > 0)
p[--i].~T();
operator delete(p);
throw;
}
或通过作用域析构函数:
size_t n = 100;
struct Guard
{
T *p;
size_t i;
Guard(size_t n) : i(), p(static_cast<T *>(operator new(sizeof(T) * n))) { }
~Guard()
{
while (i > 0)
p[--i].~T();
operator delete(p);
}
} guard(n);
for (guard.i = 0; guard.i < n; ++guard.i)
new (&guard.p[guard.i]) T(1, 2, 3);
guard.i = 0; // Successful... "commit" the changes
guard.p = NULL; // or whatever is necessary to commit the changes
(注意:此示例仅旨在显示两种技术之间的区别。我知道它不是完美的代码,所以请不要 关注这个特定的例子。它只是为了说明。)
最佳答案
使用析构函数的解决方案比显式的try/catch
更好:
关于c++ - 使用析构函数处理失败与 catch (...) { fix();扔; },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22347089/
我正在创建一个系统。我想知道的是,如果一个消息不受支持,它应该怎么做?我应该说不受支持的消息吗?我应该返回 0 还是 -1?或者我应该设置一个 errno (base->errno_)。有些消息我不关
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: incorrect stacktrace by rethrow 人们普遍认为,在 .NET 中,throw;
这是我第一次使用 Passport 。 当我尝试启动我的应用程序时,我不断收到此错误: passport.use(new LocalStrategy(Account.authenticate()));
假设我正在做一些在抛出异常时需要清理的事情。 比如我正在创建一个动态数组,我需要构造对象,但是它们的构造函数可能会抛出异常: size_t const n = 100; T *const p = st
我正在为一种非常简单的编程语言编写 BNF 语法,并使用 Flex 和 Bison 进行编译。 我只有 3 种变量和常量类型:实数、整数、字符串。 我的 .l 文件具有“ID”的 token 定义,如
我是一名优秀的程序员,十分优秀!