声明以下函数是否安全,noexcept即使v.at(idx)理论上可以抛出out_of_range异常,但实际上不是由于边界检查?
int get_value_or_default(const std::vector<int>& v, size_t idx) noexcept {
if (idx >= v.size()) {
return -1;
}
return v.at(idx);
}
Run Code Online (Sandbox Code Playgroud) 我很难理解这一点.
double compute(double x, double y) noexcept
{
if (y == 0)
throw std::domain_error("y is zero");
return x / y;
}
Run Code Online (Sandbox Code Playgroud)
这在clang中编译得很好(我没有检查过gcc),但这对我来说似乎是胡说八道.为什么编译器允许noexcept函数包含throw语句?
假设我有一个标记为的函数,noexcept但里面有一行代码可以抛出.那行代码将在try块中,异常将被捕获.这会导致什么吗?
void MyFunc() noexcept
{
try {
throw std::exception("...");
} catch (const std::exception & e) {
// I'll deal with it here...
}
}
Run Code Online (Sandbox Code Playgroud)