c++c++11lambda

What does the word capture mean in the context of lambdas?


Can somebody please provide some insights on this? Is the lambda capturing external variables, or is the outside world capturing values produced by the lambdas? What does it mean for a certain variable to be captured?


Solution

  • The lambda is capturing an outside variable.

    A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class.

    A lambda can specify whether it's passed by reference or by value. For example:

    [&] { x += 1; }       // capture by reference
    [=] { return x + 1; } // capture by value
    

    The first produces a class roughly like this:

    class foo { 
        int &x;
    public:
        foo(int &x) : x(x) {}
        void operator()() const { x += 1; }
    };
    

    The second produces a class something like this:

    class bar {
        int x;
    public:
        bar(int x) : x(x) {}
        int operator()() const { return x + 1; }
    };
    

    As with most uses of references, capturing by reference can create a dangling reference if the closure (the object of the class created by the lambda expression) out-lives the object that was captured.