Lambda Capture Clauses in C++

The general syntax for a lambda expression is as follows:

[ capture_clause ] (parameters) -> return-type  
{
definition of method
}

Here, capture clauses are defined inside the square brackets[].

Capture Clauses in lambda expressions determine how the external variables are accessed from the lambda expression. The capture clauses allow the lambda function to capture external variables and use them inside the lambda body.

There are three ways to capture external variables using the Lambda Capture clauses

  • Capture by reference
  • Capture by value
  • Capture by both reference and value (mixed capture)

Note: A lambda with an empty capture clause [ ] can only access variables which are local to it.

Lambda Capture Clause in C++

In C++, lambda expressions were introduced after C++ 11 and allowed users to create a small inline function directly without declaring functions explicitly. In this article, we will discuss how we can use capture clauses in Lambda expressions to access variables from the enclosing scope of the expressions.

Before exploring the Lambda Capture clauses make sure you are familiar with Lambda Expressions in C++.

Similar Reads

Lambda Capture Clauses in C++

The general syntax for a lambda expression is as follows:...

Examples of Lambda Captures

Example 1: Capture Values by Reference...

Conclusion

...

Contact Us