You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于C++ Lambda表达式中(4)的含义与调用方式的技术咨询

What does the (4) mean in this C++ lambda expression?

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 captures m by reference, n by value, takes an integer parameter a, and modifies m using incremented n and a.
  • The (4) is how we call this lambda immediately. It passes the integer 4 as the argument to the lambda's parameter a—just like you'd call a regular function like my_function(4).

Let's walk through exactly what happens to get your output of 5 0:

  1. Initially, m = 0 and n = 0 in main.
  2. We define the lambda, then instantly call it with 4 (so a = 4 inside the lambda).
  3. Inside the lambda:
    • Since we used mutable, we can modify the captured-by-value n—++n makes it 1.
    • We calculate 1 + 4 = 5, then assign that to m (which is captured by reference, so the original m in main gets updated to 5).
  4. The lambda finishes running. Since n was captured by value, the original n in main stays 0—changes to n inside 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:57:42