修复“lambda 没有捕获默认值”

BBa*_*ger 1 c++ lambda c++11

我第一次使用 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;
      |
Run Code Online (Sandbox Code Playgroud)

我的代码

#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();
}
Run Code Online (Sandbox Code Playgroud)

它说我的变量已声明,但为什么找不到它们?

Ant*_*esy 6

这些变量不在 lambda 的范围内,因为它们没有被捕获或作为参数传递,如错误中所示:

<source>:6:20: note: the lambda has no capture-default
    6 |     auto lambda = []() {
      | 
Run Code Online (Sandbox Code Playgroud)

您可以捕获变量(有多种可能性可以做到这一点 -> 请参阅下面的参考资料)

<source>:6:20: note: the lambda has no capture-default
    6 |     auto lambda = []() {
      | 
Run Code Online (Sandbox Code Playgroud)

或将它们作为参数传递

auto lambda = [&]() {
...
};
Run Code Online (Sandbox Code Playgroud)

我建议阅读“捕获这个词在 lambda 的上下文中意味着什么?” , cppreference.com - C++ 中的 Lambda 表达式Lambda 表达式 - 捕获子句以获取有关不同方法的更多信息。


归档时间:

查看次数:

202 次

最近记录:

2 年 前