此处的代码在类型转换后测试左值或右值:
#include <stdio.h>
template <typename T>
T const f1(T const &t) {
printf("T const \n");
return t;
}
template <typename T>
T f1(T &t) {
printf("T\n");
return t;
}
struct KK {
int a;
};
int main()
{
KK kk;
kk.a=0;
int ii;
f1(kk);
f1((KK)kk);
f1(ii);
f1((int)ii);
return 0;
}
在 gcc 中 link结果是这样的,表明右值是在类型转换后产生的:
T
T const
T
T const
但是在VC++2010中,只有类类型才是右值的结果:
T
T const
T
T
那么当类型转换为 int 时,这是编译器错误还是只是一些未定义的行为?
最佳答案
来自 expr.cast (这适用于 C++11 及更高版本)
The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue. [ Note: If T is a non-class type that is cv-qualified, the cv-qualifiers are discarded when determining the type of the resulting prvalue; see Clause [expr]. — end note ]
对于 C++98:
The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is a reference type, otherwise the result is an rvalue. [ Note: if T is a non-class type that is cv-qualified, the cv-qualifiers are ignored when determining the type of the resulting rvalue; see 3.10. — end note ]
那么,gcc就对了
从 mkaes 的评论来看,这似乎是 (可以说是有用的)MSVC 扩展
关于c++ - 转换后是右值还是左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40801765/