在C ++ 11 lambda表达式中使用超出范围变量

时间:2013-06-04 12:46:10

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

我正在玩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函数中使用外部范围变量?

1 个答案:

答案 0 :(得分:32)

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

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

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

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