【问题标题】:using out of scope variables in C++11 lambda expressions在 C++11 lambda 表达式中使用超出范围的变量
【发布时间】:2013-05-30 20:56:26
【问题描述】:

我玩 C++11 是为了好玩。我想知道为什么会这样:

//...
std::vector<P_EndPoint> agents;
P_CommunicationProtocol requestPacket;
//...
bool repeated = std::any_of(agents.begin(), agents.end(),
                    [](P_EndPoint i)->bool 
                    {return requestPacket.identity().id()==i.id();});

编译因以下错误而终止:

error: 'requestPacket' has not been declared

在前面的代码中已声明。我试过::requestPacke,也没用。

如何在 lambda 函数中使用外部范围变量?

【问题讨论】:

  • 它们在类的方法中。这不是一个好标题,也许我应该把它改成out of current scope...

标签: c++ c++11 lambda std capture


【解决方案1】:

您需要capture the variable,或者按值(使用[=] 语法)

bool repeated = std::any_of(agents.begin(), agents.end(),
                    [=](P_EndPoint i)->bool                          
                    {return requestPacket.identity().id()==i.id();});

或通过引用(使用[&amp;] 语法)

bool repeated = std::any_of(agents.begin(), agents.end(),
                    [&](P_EndPoint i)->bool 
                    {return requestPacket.identity().id()==i.id();});

请注意,正如@aschepler 指出的,global variables with static storage duration are not captured,只有函数级变量:

#include <iostream>

auto const global = 0;

int main()
{
    auto const local = 0;

    auto lam1 = [](){ return global; }; // global is always seen
    auto lam2 = [&](){ return local; }; // need to capture local

    std::cout << lam1() << "\n";
    std::cout << lam2() << "\n";
}

【讨论】:

  • Lambdas 从不捕获全局变量,只捕获函数局部变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2021-10-04
相关资源
最近更新 更多