CodeTheRobot

C++ Intermediate · Lesson 05 of 27

Lambdas: capture lists and inline callbacks

Anonymous functions, [=] vs [&] vs explicit captures, and lambdas as callbacks.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain lambdas: capture lists and inline callbacks in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A lambda is an unnamed function written where it is used: [captures](parameters) { body }. The capture list chooses which outside variables the lambda can use: [x] copies x, [&x] refers to x, [this] captures the current object, and [=] or [&] capture everything used. Prefer explicit captures.

Lambdas are how ROS 2 callbacks are written: a subscription or timer takes a lambda that runs when data arrives. A lambda that captures a reference must not outlive that variable, or it will read freed memory.

Guided lesson

Work through these steps

  1. 1.

    Read the lambdas: capture lists and inline callbacks example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

int threshold = 80;
// A local variable the lambda will use.
auto too_hot = [threshold](double temp) { return temp > threshold; };
// Capture threshold by copy and return whether temp exceeds it.
std::cout << too_hot(85.0) << '\n';
// Call the lambda like a function; prints 1 (true).
int count = 0;
// A counter the lambda will change.
auto on_message = [&count](const std::string& text) {
// Capture count by reference so the lambda can modify it.
  ++count;
// Runs each time the callback is invoked.
  std::cout << text << '\n';
// Show the message.
};
// End of the lambda.
on_message("hello");
// First call: count becomes 1.
on_message("again");
// Second call: count becomes 2.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Build and run

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

sourcecompilerprogramBUILD AND RUN

Demo for Lambdas: capture lists and inline callbacks. Expected result: 2

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <vector>

int main() {
  const int threshold = 80;
  int count = 0;
  // TODO: write a lambda too_hot that captures threshold by copy and count by reference; it adds 1 to count when temp > threshold
  for (double t : std::vector<double>{70, 85, 90, 60}) too_hot(t);
  std::cout << count << '\n';
  return 0;
}

Expected output

2
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <vector>

int main() {
  const int threshold = 80;
  int count = 0;
  auto too_hot = [threshold, &count](double temp) {
    if (temp > threshold) ++count;
  };
  for (double t : std::vector<double>{70, 85, 90, 60}) too_hot(t);
  std::cout << count << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write a function register_callback(std::function<void(int)>) that stores a callback. Register a lambda capturing a counter by reference, call it three times, then explain why capturing a local by reference would be dangerous if the callback ran after the function returned.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.