我在 return
之后错误地粘贴了一个 throw
语句,最终结果如下:
void DXManager::initialize(const std::shared_ptr<nae::Context>& ctx_ptr)
{
// ...
if (FAILED(result))
{
return throw std::exception("Failed to enumerate display mode list");
}
// ...
}
我在注意到错误之前成功构建了解决方案,我很好奇哪个规范允许上述语法。
通过阅读cppreference.com (在注释下),我明白了
The throw-expression is classified as prvalue expression of type void. Like any other expression, it may be a sub-expression in another expression, most commonly in the conditional operator:
double f(double d) { return d > 1e7 ? throw std::overflow_error("too big") : d; } // ...
但我不太确定这就是我要找的东西。
最佳答案
嗯,这是因为返回 void
的函数中的 return 语句可以有一个 void
操作数:
The expr-or-braced-init-list of a return statement is called its operand [...] A return statement with an operand of type
void
shall be used only in a function whose return type is cvvoid
.
正如您自己发现的那样,throw
表达式的类型为 void
。这个规定是为了让编写通用代码更顺畅。考虑一下:
template<typename T>
T foo() {
return T();
}
上述规则(以及定义 void()
的另一条规则)使上述模板即使在为 void
实例化时也有效。
关于c++ - 为什么在 void 函数中接受 return throw std::exception()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059418/