xui*_*in. 5 c++ exception try-catch
给出如下代码:
void f()
{
int i;
i = 0;
}
Run Code Online (Sandbox Code Playgroud)
由于简单的赋值,系统是否可能抛出异常?
[编辑:对于那些说"没有例外不能发生"的人,你能指出我的C++标准部分的方向吗?我找不到它.]
虽然你可能很难在标准中找到它的保证,但一个简单的经验法则是,任何在C中合法的东西都可能无法抛出.[编辑:我最接近直接声明这一点的是§15/ 2,其中说:
执行throw-expression的代码被称为"抛出异常;"[...]
反过来看,不执行throw-expression的代码不会抛出异常.
投掷基本上限于两种可能性:第一种是调用UB.第二种是对C++执行一些独特的操作,例如分配给重载的用户定义类型operator =
或使用new
表达式.
编辑:就任务而言,有很多方法可以抛出.显然,投入任务操作员本身就可以做到,但还有相当多的其他人.例如,如果源类型与目标类型不匹配,则可能通过源中的强制转换操作符或目标中的构造函数进行转换 - 其中任何一个都可能抛出.
有很多东西看起来像是可以抛出这样或那样的任务:
int operator"" _t(const char *) { throw 0; } // C++11 user defined literal
struct foo {
foo(int) { throw 0; }
operator int() { throw 0; }
foo& operator=(int) { throw 0; }
};
int main() {
int i;
i = 0; // can't throw
i = 0_t; // User defined literal throws
foo f = 0; // Constructor throws
i = f; // conversion operator throws
f = 0; // assignment throws
f = f; // both conversion and assignment would like to throw
}
Run Code Online (Sandbox Code Playgroud)
(包括来自C++ 11的新版本)
归档时间: |
|
查看次数: |
670 次 |
最近记录: |