Home | Projects | Notes > C++ Programming > Introduction to Lambda Expressions

Introduction to Lambda Expressions

 

Introduction

Lambda expressions were first introduced in C++11 and were later extended in C++14 and C++17. They provide a convenient way to define functionality exactly where it's needed, without writing a lot of extra code.

Types of Lambda Expressions:

 

Motivation

Prior to C++11, function objects (i.e., functors) and function pointers were commonly used to provide custom behavior, both with the Standard Template Library (STL) and in user-defined code.

What's the problem with that?

This approach often leads to the need for writing many short functions that control algorithm behavior. In the STL, these short functions are typically wrapped in small classes to create function objects. However, these classes and functions are frequently located far from where they are actually used, which can make modification, maintenance, and testing more difficult.

Additionally, compilers are generally less effective at optimizing functions that are not defined in-line.

Case Study

Best Practice with Lambda Expressions

Even though lambda expressions can replace function objects and allow us to write more concise and focused code, they cannot completely replace function objects.

A best practice with lambda expressions is to use them when the logic consists of a single statement or just a few simple statements. For more complex logic, it's better to use a function object.

Another benefit of lambda expressions is that the compiler creates a closure object from the lambda. This means we can access the environment in which the lambda was defined, which is a very powerful capability.

The compiler generates unnamed function objects behind the scenes from lambda expressions, and now you understand how they work!

 

Structure of a Lambda Expression

The structure of a lambda expression:

Examples

The following are examples of stateless lambda expressions, which have empty capture lists.