lundi 2 août 2021

Why capture lambda does not working in c++?

I am playing with the lambda expression in the c++ and I have tried few things to see outcome. I actually watched the video in cppcon Back to Basics: Lambdas from Scratch - Arthur O'Dwyer - CppCon 2019 @21:47 and started to play with lambda. As an example, I've tried this:

#include <iostream>
using namespace std;
int g = 10;//global var 'g'

//creating lambda
auto kitten = [=] () {return g+1;};
auto cat = [g=g] () {return g+1;};
// main
int main()
{
    g = 20;//modifying global variable 'g'
    cout<<"kitten: "<<kitten()<<"cat: "<<cat()<<endl;

    return 0;
}

Output of the above code is: kitten: 21cat: 11

In the above example: [g=g] means capture a data member whose name is g and whose type is the same as the outer g. As if I had written auto g=g It's a copy of g. Which makes sense when we think that (as if I had written in the form of auto g=g) so the result is 11 in our case where modification of the global g is not reflected in our local g. The result for the kitten is 21 because as far as I understand, capture everything i.e., capture all external variable by value. Then when it comes to this example by modifying first lambda as follows:

auto kitten = [] () {int g  = g; return g+1;};

Where I declared local g and assigned value from global g, Output is: kitten: 1cat: 11. But I was expecting the output as in the first example(21) because I am trying the create local g and assigning its value from global g where it is already modified to value of 20. Codes are compiled on https://techiedelight.com/compiler/ and godbolt.org with c++ (GCC 8.3.0) ( with the latest compiler [=] this is not allowed but the results are same.

At this moment, I am little confused about the concept of capturing and/or lambda.

Aucun commentaire:

Enregistrer un commentaire