这是我在 Reddit 上的一次短暂尝试中发现的:
Http://www.smallshire.org.uk/sufficientlysmall/2009/07/31/in-c-throw-is-an-expression/
基本上,作者指出在 C + + 中:
throw "error"
是一种表达方式。实际上,在 C + + 标准中,无论是在主要文本中还是在文法中,这一点都非常清楚地阐明了。然而,不清楚的是(至少对我来说)这个表达的类型是什么?我猜是“ void
”,但是对 g + + 4.4.0和 Comeau 进行了一些实验,得到了以下代码:
void f() {
}
struct S {};
int main() {
int x = 1;
const char * p1 = x == 1 ? "foo" : throw S(); // 1
const char * p2 = x == 1 ? "foo" : f(); // 2
}
编译器对//1没有问题,但对//2感到厌恶,因为条件运算符中的类型是不同的。因此,throw
表达式的类型似乎不是无效的。
那是什么?
如果你回答,请用引用标准来支持你的陈述。
This turned out not to be so much about the type of a throw expression as how the conditional operator deals with throw expressions - something I certainly didn't 感谢所有回复的人,特别是大卫 · 索恩利