在C ++中引用参考 [英] Reference of Reference in C++

查看:106
本文介绍了在C ++中引用参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每隔一段时间看到StackOverflow上的代码,询问一些涉及一个函数的重载模糊性:

  void foo(int&& param); 

我的问题是:为什么会出现?或者,你什么时候有引用参考?这与普通的旧引用有什么不同?我从来没有遇到这种现实世界的代码,所以我很好奇什么样的代码将需要这个。

解决方案

这是一个有价值的参考资料,Bjarne在此处



无耻的复制(quoting):


右值参考
$ b

右值引用是一个复合类型
,非常类似于C ++的传统
引用。为了更好地区分这些
两种类型,我们将传统的
C ++引用称为左值引用。
当使用术语引用时,
引用两种引用:
lvalue引用和rvalue引用。



引用由
形成,

  A a; A& a_ref1 = a; //一个左值引用

右值引用由
形成,放置&&后一些类型。

  A a; A&& a_ref2 = a; //一个右值引用

右值引用的行为就像
一个左值引用,可以
绑定到一个临时(一个右值),
,而你不能绑定一个(非const)
左值引用一个右值。

  a_ref3 = A(); //错误! 
A&& a_ref4 = A(); // Ok



I see code on StackOverflow every once in a while, asking about some overload ambiguity with something involving a function like:

void foo(int&& param);

My question is: Why does this even come up? Or rather, when would you ever have "a reference to a reference"? How is that any different from a plain old reference? I've never run across this in real-world code, so I'm curious as to what kind of code would need this.

解决方案

It's a rvalue reference, Bjarne describes it here.

Shameless copying ("quoting"):

The rvalue reference

An rvalue reference is a compound type very similar to C++'s traditional reference. To better distinguish these two types, we refer to a traditional C++ reference as an lvalue reference. When the term reference is used, it refers to both kinds of reference: lvalue reference and rvalue reference.

An lvalue reference is formed by placing an & after some type.

A a; A& a_ref1 = a;  // an lvalue reference

An rvalue reference is formed by placing an && after some type.

A a; A&& a_ref2 = a;  // an rvalue reference

An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.

A&  a_ref3 = A();  // Error! 
A&& a_ref4 = A();  // Ok

这篇关于在C ++中引用参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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