在C ++中访问Lambda外部的Lambda Capture初始化变量 [英] Accessing lambda capture initialized variable outside the lambda in C++

查看:108
本文介绍了在C ++中访问Lambda外部的Lambda Capture初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 14/17中,如何在lambda范围之外访问lambda捕获初始化变量?

In C++14/17, how do you access a lambda capture initialized variable outside the scope of the lambda?

来源:

#include <iostream>

using namespace std;

int main(){
    auto test = [value1 =0]() mutable {value1+=1; return value1;};
    cout << test() << endl;
    cout << test() << endl;
    //cout << value1 << endl;//error: ‘value1’ was not declared in this scope
}

输出:


1

1

2

value1 变量是否可以在 test() lambda范围之外访问? Lambda捕获初始化变量的生命周期是多少?

Is the value1 variable accessible outside the scope of the test() lambda? What is the lifetime of a lambda capture initialized variable?

尝试在Lambda外部访问 value1 会得到以下错误:未在此范围内声明'value1'

Attempting to access value1 outside the lambda gives the following error: ‘value1’ was not declared in this scope.

已与gcc版本7.3.0一起编译(Ubuntu 7.3.0-21ubuntu1〜14.04 )。

推荐答案

lambda只是对内联定义的结构和的紧凑定义operator()在该结构上重载(并用于创建该结构类型的对象)。 Lambda捕获只是此结构的成员变量,由类型的构造函数初始化。这就是C ++ lambda必须具有按值或按引用捕获的语法的原因之一。

A lambda is just a compact definition for an inline-defined struct and an operator() overload on that struct (and for creating an object of that struct's type). Lambda "captures" are just member variables of this struct, initialized by the type's constructor. This is one reason why C++ lambdas have to have syntax for capturing by value vs. by reference.

但是该结构的成员变量是私有的。而且,由于编译器生成的结构在很大程度上是实现定义的,因此标准不需要使用这些名称公开这些成员。如果需要,编译器生成的结构可以使用其他名称。

But the members variables of the struct are private. And since the compiler-generated struct is largely implementation-defined, it isn't required by the standard to expose those members with those names. The compiler-generated struct could use some other name if it wanted; the compiler would just have to remap the in-lambda usage of those names to reference the members' names.

因此,不,lambda捕获任何类型的

So no, lambda captures of any kind cannot be accessed by the world outside of that lambda. If you capture a reference to an object, then its possible for the outside world to access the same object. But you would not be accessing the same reference to that object.

这篇关于在C ++中访问Lambda外部的Lambda Capture初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆