为什么将Rvalue引用由通用引用转换为Lvalue引用 [英] Why an Rvalue Reference is Turned into Lvalue Reference by a Universal Reference

查看:94
本文介绍了为什么将Rvalue引用由通用引用转换为Lvalue引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设当通用引用参数与右值引用参数匹配时,返回右值引用参数。但是,我的测试表明,通用引用函数模板将右值引用转换为左值引用。为什么会这样?

I suppose when a universal reference parameter is matched with an rvalue reference argument, an rvalue reference argument is returned. However, my testing shows that the rvalue reference is turned into a lvalue reference by the universal reference function template. Why is it so?

#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
T f1(T&&t) {  //<-----this is a universal reference
  cout << "is_lvalue reference:" << is_lvalue_reference<T>::value << endl;
  cout << "is_rvalue reference:" << is_rvalue_reference<T>::value << endl;
  cout << "is_reference:"        << is_reference<T>::value        << endl;
  return t;
}
void f2(int&& t) {
  cout << "f2 is_lvalue reference:" << is_lvalue_reference<decltype(t)>::value << endl;
  cout << "f2 is_rvalue reference:" << is_rvalue_reference<decltype(t)>::value << endl;
  cout << "f2 is_reference:" << is_reference<decltype(t)>::value << endl;
  f1(t);

}

int main()
{
  f2(5);
  return 0;
}

在GCC和VC ++ 2010中,结果如下:

In both GCC and VC++2010, this is the result:

f2 is_lvalue reference:0
f2 is_rvalue reference:1
f2 is_reference:1
is_lvalue reference:1
is_rvalue reference:0
is_reference:1

f2 中的参数 t 是右值引用,但是当传递给 f1 ,该参数成为左值引用。它不应该在 f1 中保留右值吗?

In other words, the parameter t in f2 was an rvalue reference, but when passed to f1, the parameter became a lvalue reference. Shouldn't it retain the rvalue-ness in f1?

推荐答案

原因是命名的右值引用被视为左值。

The reason is that named rvalue references are treated as lvalues.

您应使用 t 传递给 f1 来保留右值时,在 f2 内/ move rel = nofollow noreferrer> std :: move

You should use std::move inside f2 when passing t to f1 to retain rvalueness:

void f2(int&& t) {
    f1(std::move(t));
}

在这里,您会找到很好的解释。

Here you can find a good explanation.

这篇关于为什么将Rvalue引用由通用引用转换为Lvalue引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆