Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Double Address Operator? (&&)

I'm reading STL source code and I have no idea what && address operator is supposed to do. Here is a code example from stl_vector.h:

vector& operator=(vector&& __x) // <-- Note double ampersands here {     // NB: DR 675.     this->clear();     this->swap(__x);      return *this; } 

Does "Address of Address" make any sense? Why does it have two address operators instead of just one?

like image 991
Anarki Avatar asked Dec 28 '10 20:12

Anarki


People also ask

What is && mean in C++?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 .

What is the address operator in C?

The Address Operator in C also called a pointer. This address operator is denoted by “&”. This & symbol is called an ampersand. This & is used in a unary operator.

What is double ampersand in C?

In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199).

What does == mean in C++?

The '==' operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example: 5==5 This will return true.


1 Answers

&& is new in C++11. int&& a means "a" is an r-value reference. && is normally only used to declare a parameter of a function. And it only takes a r-value expression. If you don't know what an r-value is, the simple explanation is that it doesn't have a memory address. E.g. the number 6, and character 'v' are both r-values. int a, a is an l-value, however (a+2) is an r-value. For example:

void foo(int&& a) {     //Some magical code... }  int main() {     int b;     foo(b); //Error. An rValue reference cannot be pointed to a lValue.     foo(5); //Compiles with no error.     foo(b+3); //Compiles with no error.      int&& c = b; //Error. An rValue reference cannot be pointed to a lValue.     int&& d = 5; //Compiles with no error. } 

Hope that is informative.

like image 100
Lexseal Lin Avatar answered Sep 28 '22 08:09

Lexseal Lin