问题
The code here test for lvalue or rvalue after a type cast:
#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;
}
In gcc link the result is like this indicating rvalue resulted after a type cast:
T
T const
T
T const
But in VC++2010, this is the result indicating rvalue only if it is a class type:
T
T const
T
T
So is it a compiler bug or just some undefined behaviour when type cast to int?
回答1:
From expr.cast (this is applicable from C++11 and later)
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 ]
For 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 ]
Then, gcc is right
From mkaes's comment, it seems like this is the (arguably useful) MSVC extension
来源:https://stackoverflow.com/questions/40801765/is-it-an-rvalue-or-lvalue-after-a-cast