【问题标题】:Question about c++ lambda (with non-automatic storage duration)关于 c++ lambda 的问题(具有非自动存储持续时间)
【发布时间】:2018-12-06 03:53:18
【问题描述】:

我的代码如下

#include <iostream>
#include <string>

using namespace std;

int x;

struct A
{
    auto func()
    {
        auto test([&, &x](){cout << x << endl;});
        test();
    }
};

int main()
{
   A a;
   x = 5;
   a.func();
}

我的程序如上,我是用下面的命令编译的

g++ -std=c++11 ex.cpp -o ex

但是,我收到如下警告

ex.cpp:在成员函数‘auto A::func()’中:
ex.cpp:11:19: 警告:以非自动存储持续时间捕获变量“x”
auto test([&amp;, &amp;x](){cout &lt;&lt; x &lt;&lt; endl;});
^
ex.cpp:6:5:注意:此处声明了“int x”
int x;

谁能帮我解决?

【问题讨论】:

  • x 是全局变量,不需要捕获。
  • 而且“全部捕获”也是不需要的。你实际上什么也没捕捉到。

标签: c++ lambda storage duration


【解决方案1】:

您的 lambda 实际上没有捕获任何内容:

x 是一个全局变量(如std::cout)。

只需删除捕获:

auto func()
{
    auto test([](){ std::cout << x << std::endl; });
    test();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多