HOWTO · C++

C++ 中的双与号

本教程介绍了 C++ 中双 & 符号的含义。

本页内容

本指南将讨论 C++ 中的双 & 符号。它实际上是在 C++11 的概念中。

你可能已经在声明变量时看到过双与号 (&&)。要理解这个概念的各个方面,我们需要了解 C++ 的一些基础知识。

C++ 中的双与号

要理解双与号 (&&),我们需要了解 C++ 中的 lvaluesrvalues。让我们在以下小节中理解这些术语。

C++ 中的左值

lvalue 被认为是一个对象或变量,可以占用主存储器或 RAM 中的可识别空间。例如,看看下面的代码。

int number = 10;

number 在上面的代码中被认为是一个 lvalue。我们通过将其设为指针来获取其位置/地址。

// this is pointer to varible
int *ptr_Number = &number;

// here we'll get the address of variable in memory;
cout << ptr_Number << endl;

// object example

C++ 中的 rvalue

rvalue 是在内存中没有任何可识别空间的对象或变量。它也被认为是一个临时值。

看看下面的代码。

int number = 10;

number 是上面代码中的 lvalue,但 10rvalue。如果我们尝试获取数字 10 地址,我们会得到一个错误。

// int *ptr_10 = &10;
//(error) expression must be an lvalue

在 C++11 中,双 & 符号指的是 rvalue。现在,让我们考虑两种方法。

一个带有单&符号,另一个带有双&符号。

如果你尝试将 lvalue 传递给函数,你将收到错误消息。所以基本上,双&符号的主要目的是引用 rvalues

// single ampersand sign is used to refer lvalue
int add(int &a, int &b) { return a + b; }

// double ampersand sign is used to refer rvalue

int add_(int &&a, int &&b) { return a + b; }
int main() {
  // here we pass lvalue to the function
  int num1 = 10;
  int num2 = 30;
  int sum = add(num1, num2);
  cout << sum << endl;
  // it will give the error if we pass the rvalues to that function
  //  int sum_1= add(10,30);
  //(error) initial value of reference to non-const must be an lvalue

  // c++11 provides the facility of passing rvalues by using double ampersand
  // sign
  int sum_1 = add_(10, 30);
  cout << endl;
}