C ++ Double Address Operator? (&&)

I am reading the STL source code and I have no idea what to do with the && address operator. Here is a sample code from stl_vector.h :

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

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

+58
c ++ stl operator-keyword memory-address
Dec 28 '10 at 20:14
source share
5 answers

This is C ++ 11 . In C ++ 11, the && token can be used to mean “rvalue references”.

+66
Dec 28 '10 at 20:16
source share

&& is new in C ++ 11, and this means that the function accepts an RValue-Reference - that is, a reference to an argument that is about to be destroyed.

+56
Dec 28 '10 at 20:16
source share

As mentioned in other answers, the && token in this context is new to C ++ 0x (the next C ++ standard) and is a “rvalue reference”.

Rvalue links are one of the most important things in the upcoming standard; they allow you to maintain the semantics of "move" on objects and provide perfect forwarding of function calls.

This is a rather complicated topic - one of the best presentations (it is not just fluent) - article by Stefan T. Lavavi, "Rvalue References: C ++ 0x Features in VC10, Part 2"

Please note that the article is still pretty heavy, but worth it. And although this is on the Microsoft VC ++ blog, all (or almost all) of the information is applicable to any C ++ 0x compiler.

+25
Dec 28 '10 at 20:29
source share

&& is new in C ++ 11. int&& a means that "a" is a reference to an r-value. && usually used only to declare a function parameter. And it only accepts r-value expression. If you do not know what an r-value is, a simple explanation is that it does not have a memory address. For example. number 6, and the symbol "v" - 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 this is informative.

+20
Sep 13 '16 at 23:05
source share

I believe this is a move operator. operator= - assignment operator, for example, vector x = vector y . The call to the clear() function sounds like it is deleting the contents of a vector to prevent memory leak. The operator returns a pointer to a new vector.

In this way,

 std::vector<int> a(100, 10); std::vector<int> b = a; for(unsigned int i = 0; i < b.size(); i++) { std::cout << b[i] << ' '; } 

Despite the fact that we gave the vector values, the vector b has values. This is magic operator=() !

MSDN - How to Create a Move Constructor

+1
Dec 23 '14 at 16:43
source share