通过内部&&到f(int&) [英] Passing int&& to f(int&&)

查看:156
本文介绍了通过内部&&到f(int&)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里发生了什么?为什么这是一个错误?

What is exactly happening here? Why is this an error?

void f(int &&);

int && i = 5;

f(i);

这不是有点违反直觉吗?

Isn't it a bit counterintuitive?

我认为 i 是一个右值引用,因此能够将它传递给 f()。但我收到一个错误;

I would expect i to be a rvalue reference, and so be able to pass it to f(). But I get an error;


没有从 int int&&&&&&&< / code>

no known conversion from int to int &&

code>在声明后不是一个右值引用?

So I guess i is not an rvalue reference after declaration?

推荐答案

/ em>和绑定。例如:

There's a basic distinction here between is a and binds a. For example:

void f(int &&);

声明一个函数接受一个参数,该参数只能使用右值引用初始化(类型可转换为) int

declares a function accepting a parameter that can only be initialized with an rvalue reference to a (type convertible to) int.

int && i = 5;

声明一个左值,只能使用右值引用(类型可转换为) int 。因此,简单来说,

declares an lvalue that can only be initialized with an rvalue reference to a (type convertible to) int. Thus, in simple terms,

f(i);

尝试将一个左值引用传递给 int 到只接受对 int 的右值引用的函数。

tries to pass an lvalue reference to an int to a function accepting only rvalue references to an int. So it doesn't compile.

要告诉编译器将左值转换为右值,从而在适用的情况下使用 move constructors int 的情况下),您可以使用 std :: move()

To tell the compiler to cast an lvalue to an rvalue, thereby utilizing move constructors where applicable (though not in the case of an int), you can use std::move().

f(std::move(i));

这篇关于通过内部&amp;&amp;到f(int&amp;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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