0
Why capture by value fails in lambda
Hi Refer code below: I just want a to be captured by reference where as b by value. Why does it fails to compile? https://sololearn.com/compiler-playground/c32o40MJ5397/?ref=app
6 Respostas
+ 4
int a = 10;
int b = 20;
[&a,b](){
    cout << "Hi\n";
    cout << (++a) << endl;
    cout << b << endl;
}();
+ 2
Jan right,  forgot to add that part.
+ 1
Bob_Li I made a little change to your example, so a is increased....
    int a = 10;
    int b = 20;
    [&a,b](){
    cout << "Hi\n";
    cout << (++a) << endl;
    cout << b << endl;
    }();
    
    cout << a;
0
You can do it this way........
    int a = 10;
    int b = 20;
    
    auto lam = [](int &a, int b)
    {
      cout << "Hi\n";
      cout << ++a << endl;
      cout << b << endl;
    };
    
    lam(a, b);
    cout << a;
0
Nope. I don't want to create an arguments to lambda. It should be done by capture clause only
0
Okay, here is another solution......
    int a = 10;
    int b = 20;
    int *pa = &a;
    int *pb = &b;
    
    auto lam = [pa, pb]()
    {
      cout << "Hi\n";
      cout << ++*pa << endl;
      cout << *pb << endl;
    
    };
    
    lam();
    cout << a;



