lambda 表达式捕获列表
面试考点
lambda 捕获列表是 C++11 面试高频题。面试官关注你是否理解值捕获和引用捕获的区别、mutable 的作用、C++14 初始化捕获、以及捕获 this 的坑。
核心概念
lambda 的捕获列表决定了它能访问哪些外部变量、以什么方式访问。本质上,lambda 是编译器生成的匿名类,捕获的变量就是这个类的成员变量。
[捕获列表](参数列表) -> 返回类型 { 函数体 }捕获方式一览
| 语法 | 含义 |
|---|---|
[] | 不捕获任何变量 |
[x] | 值捕获 x(拷贝) |
[&x] | 引用捕获 x |
[=] | 值捕获所有用到的变量 |
[&] | 引用捕获所有用到的变量 |
[=, &x] | 默认值捕获,x 引用捕获 |
[&, x] | 默认引用捕获,x 值捕获 |
[this] | 捕获 this 指针 |
[*this] | 值捕获当前对象(C++17) |
[x = expr] | 初始化捕获(C++14) |
基本示例
cpp
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
#include <algorithm>
// ============================
// 示例1:值捕获 vs 引用捕获
// ============================
void capture_demo() {
int x = 10;
int y = 20;
// 值捕获:lambda 内部是 x 的拷贝,修改 x 不影响外部
auto by_value = [x]() {
std::cout << "值捕获 x = " << x << std::endl;
// x = 100; // 编译错误:值捕获默认是 const 的
};
// 引用捕获:lambda 内部是 x 的引用,修改会影响外部
auto by_ref = [&x]() {
x = 100; // 修改外部的 x
std::cout << "引用捕获修改 x = " << x << std::endl;
};
// 混合捕获
auto mixed = [x, &y]() {
// x 是值捕获(不可修改),y 是引用捕获(可修改)
y = x + 30;
std::cout << "x = " << x << ", y = " << y << std::endl;
};
x = 999; // 修改 x
by_value(); // 输出 10(值捕获是捕获时的值)
by_ref(); // 修改 x 为 100
mixed(); // x = 10(捕获时的值),y 被修改
}
// ============================
// 示例2:mutable 关键字
// ============================
void mutable_demo() {
int count = 0;
// 值捕获的变量默认是 const 的
// 加 mutable 允许修改捕获的副本(不影响外部变量)
auto counter = [count]() mutable {
count++; // 修改的是 lambda 内部的副本
std::cout << "内部 count = " << count << std::endl;
};
counter(); // 内部 count = 1
counter(); // 内部 count = 2
counter(); // 内部 count = 3
std::cout << "外部 count = " << count << std::endl; // 0(没变)
}
// ============================
// 示例3:初始化捕获(C++14)
// ============================
void init_capture_demo() {
// 初始化捕获:在捕获列表中创建新变量
auto ptr = std::make_unique<int>(42);
// unique_ptr 不能拷贝,但可以移动到 lambda 中
auto lambda = [p = std::move(ptr)]() {
std::cout << "移动捕获: " << *p << std::endl;
};
lambda();
// ptr 已经被移走,不能再使用
// 用表达式初始化捕获变量
std::string name = "Hello";
auto greeting = [msg = name + " World"]() {
std::cout << msg << std::endl;
};
greeting();
// 重命名捕获变量
int very_long_variable_name = 100;
auto f = [x = very_long_variable_name]() {
std::cout << "重命名: " << x << std::endl;
};
f();
}
// ============================
// 示例4:捕获 this
// ============================
class Widget {
int value_ = 42;
public:
// [this] 捕获 this 指针(引用语义)
auto get_printer() {
return [this]() {
std::cout << "this 捕获: value_ = " << value_ << std::endl;
};
}
// [*this] 值捕获整个对象(C++17)
auto get_safe_printer() {
return [*this]() {
std::cout << "*this 捕获: value_ = " << value_ << std::endl;
};
}
// [=] 在成员函数中会隐式捕获 this(C++20 废弃)
auto get_deprecated_printer() {
// C++20 起 [=] 隐式捕获 this 产生警告
// 应该显式写 [=, this] 或 [=, *this]
return [=]() {
std::cout << "[=] 捕获: value_ = " << value_ << std::endl;
};
}
void set_value(int v) { value_ = v; }
};
void this_capture_demo() {
auto printer1 = Widget().get_printer();
// printer1(); // 危险:Widget 临时对象已销毁,this 悬空
auto printer2 = Widget().get_safe_printer();
printer2(); // 安全:*this 捕获了对象的副本
}
// ============================
// 示例5:捕获的生命周期陷阱
// ============================
std::function<int()> make_counter() {
int count = 0;
// 错误:引用捕获局部变量,函数返回后 count 已销毁
// return [&count]() { return ++count; }; // 悬空引用!
// 正确:值捕获 + mutable
return [count]() mutable { return ++count; };
}
void lifetime_demo() {
auto counter = make_counter();
std::cout << counter() << std::endl; // 1
std::cout << counter() << std::endl; // 2
std::cout << counter() << std::endl; // 3
}
// ============================
// 示例6:循环中的捕获陷阱
// ============================
void loop_capture_demo() {
std::vector<std::function<void()>> tasks;
// 错误:引用捕获循环变量
// for (int i = 0; i < 3; i++) {
// tasks.push_back([&i]() { std::cout << i << " "; });
// }
// 输出可能都是 3(循环结束后的值)
// 正确:值捕获循环变量
for (int i = 0; i < 3; i++) {
tasks.push_back([i]() { std::cout << i << " "; });
}
for (auto& task : tasks) {
task(); // 0 1 2
}
std::cout << std::endl;
}
int main() {
std::cout << "=== 值/引用捕获 ===" << std::endl;
capture_demo();
std::cout << "\n=== mutable ===" << std::endl;
mutable_demo();
std::cout << "\n=== 初始化捕获 ===" << std::endl;
init_capture_demo();
std::cout << "\n=== this 捕获 ===" << std::endl;
this_capture_demo();
std::cout << "\n=== 生命周期 ===" << std::endl;
lifetime_demo();
std::cout << "\n=== 循环捕获 ===" << std::endl;
loop_capture_demo();
return 0;
}常见问题
值捕获的变量为什么不能修改?
因为 lambda 的 operator() 默认是 const 的。值捕获的变量相当于类的成员变量,const 成员函数不能修改成员。加 mutable 关键字让 operator() 变成非 const,就可以修改了。但修改的是内部副本,不影响外部原始变量。
[=] 和 [&] 哪个更好?
两个都不推荐在复杂场景中使用。显式列出捕获的变量更安全、更清晰。[=] 可能隐式捕获 this(C++20 废弃了这种行为),[&] 可能引用到已销毁的局部变量。
C++14 初始化捕获解决了什么问题?
解决了 C++11 无法移动捕获的问题。unique_ptr 不能拷贝,C++11 只有值捕获(拷贝)和引用捕获,无法把 unique_ptr 移入 lambda。C++14 的 [p = std::move(ptr)] 解决了这个问题。
适用场景
- STL 算法的自定义操作
- 异步回调(需要注意生命周期)
- 事件处理器
- 闭包和函数式编程
注意事项
- 引用捕获的变量必须在 lambda 使用时仍然存活
- 循环中使用引用捕获要特别小心
- [=] 在成员函数中会隐式捕获 this(C++20 废弃)
- 使用 [*this] 值捕获对象副本更安全
- lambda 存储到 std::function 或传到异步操作时,优先值捕获
总结
lambda 捕获列表决定了外部变量如何进入 lambda 内部。值捕获创建副本(默认 const,加 mutable 可修改副本),引用捕获直接引用原始变量。C++14 的初始化捕获支持移动语义和表达式初始化。面试中最常考的陷阱:引用捕获局部变量导致悬空引用、循环中引用捕获变量、[=] 隐式捕获 this。写 lambda 时优先显式列出捕获变量,异步场景优先值捕获。