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

后端 未结 1 2027
感动是毒
感动是毒 2021-02-05 13:02

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

//...
std::vector agents;
P_CommunicationProtocol requestPacket;
//...
bool r         


        
相关标签:
1条回答
  • 2021-02-05 13:18

    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";
    }
    
    0 讨论(0)
提交回复
热议问题