using out of scope variables in C++11 lambda expressions

廉价感情. 提交于 2019-12-31 20:30:30

问题


I'm playing with C++11 for fun. I'm wondering why this happens:

//...
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();});

Compilation terminates with this error:

error: 'requestPacket' has not been declared

Which is declared earlier in code. I tried ::requestPacke and it doesn't worked too.

How can I use an external scope variable inside a lambda function?


回答1:


You need to capture the variable, either by value (using the [=] syntax)

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

or by reference (using the [&] syntax)

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

Note that as @aschepler points out, global variables with static storage duration are not captured, only function-level variables:

#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";
}


来源:https://stackoverflow.com/questions/16918231/using-out-of-scope-variables-in-c11-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!