为什么可以将右值间接绑定到左值引用,而不能直接绑定呢? [英] Why can you indirectly bind an rvalue to an lvalue reference but not directly?

查看:182
本文介绍了为什么可以将右值间接绑定到左值引用,而不能直接绑定呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的了解,您无法将一个右值的表达式绑定到左值引用。但是,我看到的是可以将右值绑定到右值引用,并且由于命名的右值引用本质上是左值,因此可以将其绑定到左值引用。不允许将右值绑定到左值引用的原因是什么?

From what I've read and seen you cannot bind an expression that is an rvalue to an lvalue reference. What I have seen however is that you can bind an rvalue to an rvalue reference and since a named rvalue reference is inherently an lvalue, you can bind it to an lvalue reference. What is the reason behind disallowing binding an rvalue to an lvalue reference. Is it for optimization purposes?

以这个示例为例:

#include <iostream>

using std::cout;

void bar ( int& b ) {

    cout << "bar " << b << "\n";
    b = 3;
}

void foo ( int&& a ) {

    cout << a << "\n";
    bar(a);
    cout << a << "\n";
}

int main ( int argc, char ** argv ) {

    foo(1);
}


推荐答案

这是C ++的基本规则并且可以防止错误:

It's a fundamental rule of C++ and it prevents bugs:

int foo();

int& x = 3;      // whoops
int& y = foo();  // whoops (sometimes)






右值引用 (一组类型;不要与实际的 rvalues 混淆)是为了至少使您可以执行此操作,如果您确实想要:


"Rvalue references" (a set of types; not to be confused with actual rvalues) were created at least in part so that you can still do this if you really want to:

int&& x = 3;     // oh, go on then *sigh*
int&& y = foo(); // you'd better be sure!

在前面的示例中,我绑定(或尝试绑定)由右值表达式引用的对象

In the previous examples, I bind (or attempt to bind) objects "referenced" by an rvalue expression to a reference.

现在,我将用左值表达式命名的对象绑定到引用:

Now, I shall bind the object named by an lvalue expression to a reference:

int i = foo();

int& x = i;      // no problem michael

并确保您真的从左值表达式中获取右值引用,引入名称难以置信的 std :: move

And to make sure that you really meant to obtain an rvalue reference from an lvalue expression, introducing the incredibly poorly-named std::move:

int&& x = std::move(i);  // doesn't move anything

这些后来的规则比原先的基本规则要晚很多

These later rules came much, much later than the original, fundamental rule that has doubtless prevented many bugs over the past twenty years.

请注意,Visual Studio过去一直接受 T& x = bar()其中 T 是用户定义的类型;走吧。

Note that Visual Studio has historically accepted T& x = bar() where T is a user-defined type; go figure.

这篇关于为什么可以将右值间接绑定到左值引用,而不能直接绑定呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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