c++ - 为什么在 void 函数中接受 return throw std::exception()?

标签 c++ visual-studio exception return prvalue

我在 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 操作数:

[stmt.return]/2

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 cv void.

正如您自己发现的那样,throw 表达式的类型为 void。这个规定是为了让编写通用代码更顺畅。考虑一下:

template<typename T>
T foo() {
    return T();
}

上述规则(以及定义 void() 的另一条规则)使上述模板即使在为 void 实例化时也有效。

关于c++ - 为什么在 void 函数中接受 return throw std::exception()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059418/

相关文章:

visual-studio - Visual Studio makecert DES3 证书

c - 有没有办法在 Visual Studio 的控制台应用程序中执行命令而不选择它?

c# - 如何在即时窗口中轻松查看数据表或数据 View 的内容

c++ - 在 C++ 中转换为 double 时处理异常

delphi - 如何使用 EurekaLog 将调用堆栈信息传递给异常?

c++ - 为什么这个模板递归无法编译?

c++ - 识别字符串中的下一个字符是否大写

c# - 具有IEnumerable <Brush>作为ItemsSource和SelectedItem异常的ComboBox

c++ - 如何返回私有(private)指针成员变量

c++ - 使用const bool删除调试信息时的编译器优化