Quick Q: c++ lambda capture by value

Quick A: A capture by value is a copy.

Recently on SO:

c++ lambda capture by value

That's because the variable is captured by value (i.e. copied) only once, when you define the lambda. It's not "updated" as you may believe. The code is roughly equivalent to:

#include <iostream>

int x = 0;
struct Lambda
{
    int _internal_x; // this is used to "capture" x ONLY ONCE
    Lambda(): _internal_x(x) {} // we "capture" it at construction, no updates after
    void operator()() const
    {
        std::cout << _internal_x << std::endl;
    }
} qqq;

int main()
{
    qqq();
    x = 77; // this has no effect on the internal state of the lambda
    qqq();
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.