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

30th Jan 2025, 8:18 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 ответов
+ 4
int a = 10; int b = 20; [&a,b](){ cout << "Hi\n"; cout << (++a) << endl; cout << b << endl; }();
30th Jan 2025, 11:32 AM
Bob_Li
Bob_Li - avatar
+ 2
Jan right, forgot to add that part.
30th Jan 2025, 11:49 AM
Bob_Li
Bob_Li - avatar
+ 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;
30th Jan 2025, 11:45 AM
Jan
Jan - avatar
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;
30th Jan 2025, 9:51 AM
Jan
Jan - avatar
0
Nope. I don't want to create an arguments to lambda. It should be done by capture clause only
30th Jan 2025, 10:13 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
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;
30th Jan 2025, 11:27 AM
Jan
Jan - avatar