在C ++中,如果throw是一个表达式,它的类型是什么? [英] In C++, if throw is an expression, what is its type?

查看:987
本文介绍了在C ++中,如果throw是一个表达式,它的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个简短报告中选择了这项功能:



http://www.smallshire.org.uk/sufficientlysmall/2009/07/31/in-c-throw-is-an-表达式/



基本上,作者指出在C ++中:

 code> throwerror

是一个表达式。这在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但barfed on / / 2,因为条件运算符中的类型不同。因此, throw 表达式的类型似乎不是无效的。



那么是什么呢? >

如果您回答,请使用标准的报价备份您的报表。






throw表达式如何条件运算符处理throw表达式 - 我当然没有
知道在今天之前。

解决方案

根据标准,5.16第2段点,第二个或第三个操作数(但不是两个)是一个throw-expression(15.1);结果是另一个的类型,是一个右值。因此,条件运算符不关心throw-expression是什么类型,而只使用其他类型。



事实上,15.1,第1段明确地说 throw-expression的类型为void。


I picked this up in one of my brief forays to reddit:

http://www.smallshire.org.uk/sufficientlysmall/2009/07/31/in-c-throw-is-an-expression/

Basically, the author points out that in C++:

throw "error"

is an expression. This is actually fairly clearly spelt out in the C++ Standard, both in the main text and the grammar. However, what is not clear (to me at least) is what is the type of the expression? I guessed "void", but a bit of experimenting with g++ 4.4.0 and Comeau yielded this code:

    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
    }

The compilers had no problem with //1 but barfed on //2 because the the types in the conditional operator are different. So the type of a throw expression does not seem to be void.

So what is it?

If you answer, please back up your statements with quotes from the Standard.


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 know about before today. Thanks to all who replied, but particularly to David Thornley.

解决方案

According to the standard, 5.16 paragraph 2 first point, "The second or the third operand (but not both) is a throw-expression (15.1); the result is of the type of the other and is an rvalue." Therefore, the conditional operator doesn't care what type a throw-expression is, but will just use the other type.

In fact, 15.1, paragraph 1 says explicitly "A throw-expression is of type void."

这篇关于在C ++中,如果throw是一个表达式,它的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆