gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:33:23 26 4
gpt4 key购买 nike

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

最佳答案

您需要 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";
}

关于c++ - 在 C++11 lambda 表达式中使用超出范围的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16918231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com