dimanche 28 mai 2023

How does C++ store lambda functions and their scope outside of a method? [duplicate]

Understanding the storage of lambda functions in C++

Hello I am learning C++ and came across a code where they used a lambda function in an object's constructor and saved it in a function pointer. The code is as follows

#include <cstdio>
#include <functional>

class A{
public:
    A() : counter {} {
        lambda = [this](int update){
            this->counter += update;
            return this->counter;
        }; // This lambda is persisting even after exiting the method, which seems wrong

        int temp = 10; //This address gets destroyed after the function call
        int_ptr = &temp;
    }

    std::function<int(int)> lambda;
    int counter;
    int* int_ptr;
};

int main(){
    A a1;
    auto res = a1.lambda(20);
    res = a1.lambda(20); // Working
    printf("Result of the lambda = %d\n", res);
    printf("Value pointed by the pointer = %d\n", *a1.int_ptr); //Improper Useage
    return 0;
}

My question is that the lambda definition we defined in the constructor should not be valid outside the constructor since lambda's scope is automatic. In the same note the '''temp''' variable's scope is also automatic and even if we have access to its address outside the function's scope accessing it is wrong.

Shouldn't the same also be valid for the lambda ?

Aucun commentaire:

Enregistrer un commentaire