gpt4 book ai didi

c++ - 为什么是抛出一个表达式?

转载 作者:IT老高 更新时间:2023-10-28 22:14:44 27 4
gpt4 key购买 nike

以下帖子讨论了 throw 表达式的类型:In C++, if throw is an expression, what is its type? .我想澄清一个更基本的事情:为什么 throw 首先应该是一个表达式而不是一个(非表达式)语句,就像 return 一样?我的意思是,有人想写类似 auto x = throw std::runtime_error("Error message") 的东西吗?

最佳答案

如果 throw 是一个语句,则不能将其与条件运算符一起使用。

return success()
? computation()
: throw std::runtime_error("oops");

注意:这可能会或可能不会使用外部代码混淆。

编辑:一个有用的案例是在 C++11 的严格 constexpr 函数中,它只能包含一条指令。感谢@dyp 的洞察力!

关于c++ - 为什么是抛出一个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31201102/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com