c++ - 转换后是右值还是左值

标签 c++ compiler-bug lvalue-to-rvalue

此处的代码在类型转换后测试左值或右值:

#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/

相关文章:

c++ - 调用 qExec "no known conversion for argument 1 to QObject"时出错

c++ - Clang vs G++ 左值到右值转换

c++ - 为什么这个私有(private)模板函数可以编译? -> 编译器错误 VS 2009

c++ - ISO C 中数组的左值到右值转换

c++ - 理解左值到右值转换的例子

c++ - 如何用 Cereal 序列化 boost::uuid

c++ - Floyd 的环路查找算法什么时候会失败?

c++ - 如何从字符串中间提取子字符串

c++ - 有人可以向我解释这是未定义的行为吗?

c++ - 由于 std::function 而导致构造函数重载的歧义