简体   繁体   中英

about Initialized Captures of the C++14 lambdas

Why the value x is updated to 6, and y is initialized to 7?

Could anybody give me some clues?

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

In the capture group:

[&r = x, x = x+1]

r is a reference to x , so any changes to r are reflected in x . On the other hand, the left hand side x in the capture group, is a copy of x+1 , where the right hand side x comes from outside the lambda.

Since the confusion is coming about from the fact that lambda capture syntax, is different than regular assignment syntax, changing the name of this copy will make it clearer what's happening:

int x = 5;
auto y = [&r = x, x_copy = x+1]() ->int {  // x_copy is 5
            r += 2;     // changes x
            return x_copy + 2;    // returns 7
         }(); 

This is equivalent to your example, so you can see that the only change to x is via r , so it becomes 6 . The local x_copy is initialized to 5 , and then the lambda returns x_copy + 2 , which is 7 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM