Is there a way, when writing a lambda function within a member function, to capture fields of the enclosing class by value? The default catch-all = doesn’t work because when I reference the variable inside the lambda I get instead a dereferencing from the captured this pointer, as well as explicitly naming the variable in the capture list, because I get two compile error: capture of non-variable <name>, and ‘this’ was not captured for this lambda function
Is there a way, when writing a lambda function within a member function, to
Share
No, data members cannot be captured by value. A lambda can capture only two kinds of things:
thispointer, andAs has been noted by ildjarn in the comments, you can create a local variable with a copy of the value of the data member, and capture that local variable by value.
I would argue that if explicit by-value capture of a data member was allowed, it could prove confusing, since the behavior of explicit capture would differ from that of implicit capture. For example, given an accessible data member of type
intnamedm, it would be odd that the following would produce different results: