user13351501
user13351501

Reputation:

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.

Upvotes: 2

Views: 80

Answers (1)

cigien
cigien

Reputation: 60238

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.

Upvotes: 2

Related Questions