C++ Lambda Expressions
Pass a threshold rule into an algorithm and distinguish copied captures from borrowed references.
How it works
A lambda creates a callable object containing the state it captures. A value capture keeps its own value, while a reference capture borrows a caller object and cannot outlive that object safely. Capture only what the callable needs so its dependencies are visible. For asynchronous or stored work, lifetime questions matter more than the short syntax. A stateless callback can also be an ordinary function; choose the form that makes the contract easiest to read.
Run it locally
Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror lambdas.cpp -o lessonOn Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.
Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.
Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> durations{20, 45, 65};
int limit{40};
auto exceeds = [limit](int value) { return value > limit; };
limit = 100;
std::cout << "Above captured limit: " << std::ranges::count_if(durations, exceeds) << '\n';
}
Expected result
Above captured limit: 2
The captured value remains forty even after the original variable changes. Two durations exceed that captured threshold. The algorithm uses the callable synchronously and does not retain references to elements afterwards. Capturing this in a member function still borrows the enclosing object unless a different ownership strategy is chosen explicitly.
Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.