关于C++ Lambda表达式中(4)的含义与调用方式的技术咨询
Ah, great question! That (4) at the end of your lambda line is how you immediately invoke the lambda function right after defining it. Let's break this down step by step using your code.
First, here's your code for reference:
#include <iostream> using namespace std; int main() { int m = 0; int n = 0; [&, n] (int a) mutable { m = ++n + a; }(4); cout << m << endl << n << endl; }
Let's break down the lambda and that trailing (4):
- The lambda itself is everything from
[&, n]to{ m = ++n + a; }: this defines a small, anonymous function that capturesmby reference,nby value, takes an integer parametera, and modifiesmusing incrementednanda. - The
(4)is how we call this lambda immediately. It passes the integer4as the argument to the lambda's parametera—just like you'd call a regular function likemy_function(4).
Let's walk through exactly what happens to get your output of 5 0:
- Initially,
m = 0andn = 0inmain. - We define the lambda, then instantly call it with
4(soa = 4inside the lambda). - Inside the lambda:
- Since we used
mutable, we can modify the captured-by-valuen—++nmakes it 1. - We calculate
1 + 4 = 5, then assign that tom(which is captured by reference, so the originalminmaingets updated to 5).
- Since we used
- The lambda finishes running. Since
nwas captured by value, the originalninmainstays 0—changes toninside the lambda don't affect the outer variable.
How to use this immediate invocation pattern
This is useful when you need a tiny, one-off piece of logic that you don't want to reuse later. It's like creating a disposable function that runs right away.
Here's another simple example to illustrate:
#include <iostream> using namespace std; int main() { // Define a lambda that adds two numbers, call it immediately with 10 and 20 int sum = [](int x, int y) { return x + y; }(10, 20); cout << "Sum is: " << sum << endl; // Outputs "Sum is: 30" }
Here, we don't assign the lambda to a variable—we just define it and call it right away, storing the result directly in sum.
内容的提问来源于stack exchange,提问作者aliceangel

