C++ Succinctly: Lambda Expressions

Lambdas

No-Capture Lambdas

I assume that you have experience with lambdas from C#, so what we will do here is cover the syntax that C++ has adopted. All code snippets are from the same file in the same sample.

Sample: LambdaSample\LambdaSample.cpp

Lambdas with Parameters


Specifying a Lambda’s Return Type

The trailing return type here is -> int after the parameter specification.


Capturing Outside Variables


Lambdas in Class-Member Functions

When you use a lambda in a class-member function, you cannot use a default capture by reference. This is because the lambda will be provided with a this pointer, and it must be copied. Also, when dealing with reference-counted smart pointers, it’s common to run into problems with the lambda holding a reference to the class. Usually you will never get back to a reference count of zero, causing a memory leak in your program.

Conclusion

If you're familiar with lambda expressions in C#, then you shouldn't have a hard time getting used to the syntax in C++. In the next article, we take a look at the C++ Standard Library.

This lesson represents a chapter from C++ Succinctly, a free eBook from the team at Syncfusion.
Tags:

Comments

Related Articles