可以说我有一个像这样的构造函数
Something(SomethingElse) noexcept : member{SomethingElse, something_that_might_throw()} {
...
}
如果
noexcept
的构造可以抛出,在这种情况下member
可以吗?在上面的示例中,成员变量member
是我不知道的类型。附带说明:使用
noexcept
时是否还需要担心其他边缘情况? 最佳答案
#UPDATE:(基于您的编辑):原始答案适用于该功能块范围内的所有内容(包括构造函数,包括构造函数初始化列表)。你为什么不try代码,看看。 :-)
#原始答案
Something(SomethingElse) : member{SomethingElse} noexcept {
...
}
您的代码不会以这种方式编译。
noexcept
在冒号:
之前Something(SomethingElse) noexcept : member{SomethingElse} {
...
}
对你的问题:
不,这是not okay。
noexcept
说明符 promise 不会出现异常,不会离开该函数或构造函数。如果离开,运行时将终止您的程序。这适用于构造函数。
尽管
try..catch
块,以下代码仍被终止:struct Base {
Base(){}
Base(int){ throw int(5); }
};
struct Derived : public Base {
Derived(int a) noexcept : Base(a) {}
};
int main()
{
try{
Derived d(45);
} catch(...) {}
return 0;
}
输出:
terminate called after throwing an instance of 'int'
bash: line 7: 7454 Aborted (core dumped) ./a.out
看到它Live on Coliru
但是,如果删除
noexcept
规范,则不会突然结束程序,异常处理将继续正常进行。 :-)。如果您在生产环境中执行此类操作,甚至在具有许多贡献者的大型代码库中进行操作,我将使您思考后果。如果不确定函数/构造函数块中所有语句的异常保证,请不要使用
noexcept
关于c++ - noexcept是否适用于从初始化程序列表传播的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38818501/