Is it an Rvalue or Lvalue After a Cast

有些话、适合烂在心里 提交于 2021-02-11 11:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!