有人可以解释为什么两个编译器都在第二个示例中抛出错误而只有 gcc 在第一个示例中抛出错误吗?它是否与static_cast作为 xvalue的结果有关?
int& example1 = reinterpret_cast<int&>(static_cast<int&&>(10));
//(gcc 10.2) error: invalid cast of an rvalue expression of type 'int' to type 'int&'
//(clang 11.0.0) no errors
int& example2 = reinterpret_cast<int&>(10);
//(gcc 10.2) error: invalid cast of an rvalue expression of type 'int' to type 'int&'
//(clang 11.0.0) error: reinterpret_cast from rvalue to reference type 'int &'
Run Code Online (Sandbox Code Playgroud)
我也不确定,但我认为第一个例子是格式良好的,因为根据标准,xvalue 是 glvalue 的一种类型,对吧?并且标准的这个[expr.reinterpret.cast]/11部分说我应该能够将 T1 泛左值转换为“对 T2 的引用”类型,在这种情况下,T1 与 T2 的类型相同。