Capturing variables 🕸️

The key thing to know, is that only automatic variables can be captured. This is any local variable to your function, including the this pointer. These are pushed on and off the stack, and automatically destructed when you leave the current function.

Do [=] and [&] capture all surrounding variables?

No, this is a common misconception!

They will capture every variable that is used in the function definition, and no more. Your coding style may dictate you should explicitly name each captured variable however.

Can I have default capture variable values?

Yes, but only in C++14.

What’s so special about capturing this?

Nothing at all. this is a pointer to the current object, and is captured explicitly or implicitly like any other variable. Remember that when writing class code, you can access member variables without writing this-> . This omission is the cause of some confusion with lambdas in classes.

In both of the following cases, you are capturing a pointer by value, and then dereferencing it.

Why can’t I capture a static reference?

You can, in C++14 and higher. However, a lambda can only capture automatic variables, and a static variable, by definition, is not automatic.

You don’t need to capture static variables as they always have the same address in memory. It isn’t required — just use the static variable directly.

Note, some compilers may have static-capturing support before C++14 and warn as such, but the point still stands that you do not need to capture them.

Why can’t I capture class member variables?

You can, but recall that you can only capture automatic variables. This means you cannot explicitly capture member variables, because they’re actually behind a dereferenced pointer.

To access member variables, you need to capture this , whether explicitly or implicitly.

I want to capture some variables by value, and others by reference.

This is perfectly valid, use the following: