2

What is wrong with the syntax here? I follow this resource.

char x = 'a', y = 'a';

[&x,=y]() { // error: expected identifier before '=' token
  ++x; ++y; // error: 'y' is not captured
}();

I use MinGW g++ 4.5.2 command line compiler with -std=c++0x

clarification: I'd like to pass y by value.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 4
    to increment the value of `y`, it has to be captured by reference. To capture by value just writing `y` is sufficient. no need to write `=y' – A. K. Aug 08 '12 at 14:25
  • @AdityaKumar all true but the OP is just trying to compile an example from a blog post where the blog author specifically passed the second parameter by value to show that the effect of the increment does not affect the closed over variable (because pass by value is a copy). – Ray Toal Aug 08 '12 at 14:34
  • 1
    Capture by value by default cannot be modified. Various questions about it, e.g. http://stackoverflow.com/questions/5501959/why-does-c0xs-lambda-require-mutable-keyword-for-capture-by-value-by-defau – BoBTFish Aug 08 '12 at 14:37

1 Answers1

4
char x = 'a', y = 'a';

[&x,y]() mutable{
  ++x; ++y;
}();

Live example.

Is the correct code. To capture a variably by-value, just write its name. To allow modification of by-value captures, the lambda needs to be marked mutable, otherwise the operator() is marked const.

§5.1.2 [expr.prim.lambda] p5

[...] This function call operator is declared const (9.3.1) if and only if the lambda-expression’s parameter-declaration-clause is not followed by mutable. [...]

Xeo
  • 129,499
  • 52
  • 291
  • 397