mercredi 2 août 2023

Does a C++ lambda have a limited life?

The following C++ code prints 11.1 then crashes. The lambda function seems to be called correctly inside the constructor, but then later, that same function no longer works! Why is this? Does the lambda have a limited lifespan?

class LambdaStore
{
public:
    LambdaStore(const std::function<void(float)>& _fn)
    : fn(_fn)
    {
        fn(11.1f);    // works
    }

    void ExecuteStoredLambda()
    {
        fn(99.9f);    // crashes
    }

private:
    const std::function<void(float)>& fn;
};

void main()
{
    LambdaStore lambdaStore([](float a) {cout << a << endl; });

    lambdaStore.ExecuteStoredLambda();
}

Aucun commentaire:

Enregistrer un commentaire