C++ 中的抛出和三元运算符
以下代码可以使用 G++ 4.6.1 进行编译,但不能使用 Visual Studio 2008
return (m_something == 0) ?
throw std::logic_error("Something wrong happened") : m_something;
进行编译。事实上,Visual Studio 编译器会发生内部崩溃。
我想知道这是否是标准 C++,为什么它不能用 Visual Studio 编译,但可以用 G++ 编译?
The following code compiles with G++ 4.6.1, but not with Visual Studio 2008
return (m_something == 0) ?
throw std::logic_error("Something wrong happened") : m_something;
The fact is the Visual Studio compiler performs an internal crash.
I want to know if this is standard C++ and why it doesn't compile with Visual Studio, but does with G++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是标准的C++。条件表达式中的 then/else 表达式中的一个(或两个)允许改为 throw 表达式 (C++98 5.16/2)。
如果 Visual Studio 在编译时崩溃...那似乎很不幸!
It is standard C++. Either (or both) of the then/else expressions in a conditional expression is allowed to be a throw-expression instead (C++98 5.16/2).
If Visual Studio crashes when compiling it... that would seem to be unfortunate!
Comeau 编译它没有错误(这是我的最小可编译测试用例):
这是标准允许的很好的证据。事实上,MSVC 崩溃了,而不是因错误而彻底失败。
中得到了修复
此外,它似乎在 VC++ 2010和 x64 版本
:如果可能,请升级您的编译器,这远不是 2010 年修复的唯一错误。
Comeau compiles it without errors (here's my minimal compilable test case):
which is pretty good evidence that it's allowed by the standard. So is the fact that MSVC crashes, rather than failing cleanly with an error.
Also, it appears to be fixed in VC++ 2010
and x64 version:
Upgrade your compiler if possible, this is far from the only bug fixed in 2010.
来自 C++11 二月草案
看来
throw
算作计算为void
,并且这是允许的。From the C++11 February Draft
It appears that
throw
counts as evaluating to avoid
, and that this is allowed.内部崩溃可以被视为 Visual Studio 的错误。编译器永远不应该因为正在编译的代码而崩溃。
这是三元运算符的一种非常奇怪的用法,在返回之前使用一个简单的 if 是一个更好的习惯用法:
The internal crash can be considered a bug of Visual Studio. A compiler should never crash because of the code being compiled.
This is a very strange usage of the ternary operator, a simple if before the return would be a much preferable idiom: