修复‘lambda has no capture-default’错误:Lambda无法访问外部变量
Lambda表达式无法访问外部变量的问题解决
编译时出现如下错误:
<source>: In lambda function: <source>:7:19: error: 'x' is not captured 7 | int sum = x + y; | ^ <source>:6:20: note: the lambda has no capture-default 6 | auto lambda = []() { | ^ <source>:4:9: note: 'int x' declared here 4 | int x = 5, y = 10; | ^ <source>:7:23: error: 'y' is not captured 7 | int sum = x + y; | ^ <source>:6:20: note: the lambda has no capture-default 6 | auto lambda = []() { | ^ <source>:4:16: note: 'int y' declared here 4 | int x = 5, y = 10; |
对应的代码:
#include <iostream> int main() { int x = 5, y = 10; auto lambda = []() { int sum = x + y; std::cout << "Sum of x and y is: " << sum << std::endl; }; lambda(); }
问题原因
Lambda表达式的[]是捕获列表,默认空列表意味着不捕获任何外部变量。Lambda本质是匿名函数对象,只有通过捕获列表指定的外部变量,才会被作为成员变量包含到这个函数对象中,供内部代码访问,所以空捕获列表下无法直接访问外部的x和y。
解决方法
根据需求选择合适的捕获方式:
- 值捕获:将外部变量的值复制到lambda内部,适合变量无需被修改的场景
#include <iostream> int main() { int x = 5, y = 10; // 捕获x和y的值 auto lambda = [x, y]() { int sum = x + y; std::cout << "Sum of x and y is: " << sum << std::endl; }; lambda(); }
- 引用捕获:直接引用外部变量,适合需要修改外部变量或避免复制的场景
#include <iostream> int main() { int x = 5, y = 10; // 捕获x和y的引用 auto lambda = [&x, &y]() { int sum = x + y; std::cout << "Sum of x and y is: " << sum << std::endl; // 可以直接修改外部变量 x += 1; }; lambda(); std::cout << "Modified x: " << x << std::endl; // 输出6 }
- 批量捕获:一次性捕获所有外部变量,值捕获用
[=],引用捕获用[&]
#include <iostream> int main() { int x = 5, y = 10; // 值捕获所有外部变量 auto lambda = [=]() { int sum = x + y; std::cout << "Sum of x and y is: " << sum << std::endl; }; lambda(); }
内容的提问来源于stack exchange,提问作者BBadger
相关产品推荐
相关产品推荐

