C++ lambda capture is the syntax that lets a lambda expression bring outer-scope variables into its body either by copy ([=]) or by reference ([&]). Choosing the wrong capture mode when returning or storing a lambda can leave a dangling reference to a variable whose lifetime has already ended.
Summary
[=] copies captured variables when the lambda is created, while [&] references the original variables. If you modify a variable after creating the lambda, [=] sees the old value and [&] sees the updated value. Whenever a lambda outlives the variable (returned from a function, stored, or passed to another thread), reference capture dangles, so you should capture by value.
What is C++ lambda capture?
One-line answer: C++ lambda capture is the syntax that lets the unnamed function object (closure) created by a lambda expression hold outer-scope variables by copy or by reference.
According to the cppreference “Lambda expressions” documentation, a lambda expression creates a closure: an unnamed function object that can capture variables in scope. The capture list inside square brackets specifies which variables are captured and how.
[]: captures nothing.[=]: captures outer variables used in the lambda body by copy by default.[&]: captures outer variables used in the lambda body by reference by default.[x]: captures onlyxby copy.[&x]: captures onlyxby reference.[=, &x]: captures by copy by default, but capturesxby reference.
To see how the compiler turns a lambda into a class under the hood, check What Is C++ Insights? How to See the Code Your Compiler Hides (Lambdas, Range-for).
What is the difference between [=] and [&]?
One-line answer: [=] initializes closure members with copies when the lambda expression is evaluated, whereas [&] accesses the original object by reference.
When captured by copy ([=] or variable names without &), the closure holds member copies initialized at the moment the lambda expression is evaluated. When captured by reference ([&] or &name), the lambda body accesses the original object directly. Without mutable, the closure’s operator() is const, so copies captured by value cannot be modified inside the body; adding mutable allows modifying those copies while leaving the original variable unchanged.
Here is lambda_capture.cpp, compiled without warnings using g++ -std=c++17 -Wall lambda_capture.cpp on g++ (Debian 14.2.0-19) 14.2.0 (the inline comments copy x on creation, reference x, and modify only the copy).
#include <cstdio>
int main() {
int x = 1;
auto by_value = [=] { return x; }; // 만들 때 x를 복사
auto by_ref = [&] { return x; }; // x를 참조
x = 42;
std::printf("by_value=%d by_ref=%d\n", by_value(), by_ref());
int counter = 0;
auto inc = [counter]() mutable { return ++counter; }; // 복사본만 바뀜
inc(); inc();
std::printf("inc()=%d counter=%d\n", inc(), counter);
}
Running the program prints:
by_value=1 by_ref=42
inc()=3 counter=0
by_valuecopiedxwhen the lambda was created (1), so assigningx = 42;later does not change its return value of1.by_refrefers to the originalx, so it returns the updated value42.incis markedmutable, so calling it three times increments its internal copy to3while the outercounterremains0.
When does a dangling reference occur?
One-line answer: If an entity is captured by reference and operator() is called after that entity’s lifetime has ended, the reference dangles and triggers undefined behavior (UB).
As documented on cppreference, closures do not extend the lifetime of objects captured by reference, and the same rule applies to *this captured via this. Returning a lambda that captured a local variable by reference means the local variable is destroyed when the function returns, leaving the closure with a dangling reference.
Below is lambda_dangling.cpp, which captures the local variable count by reference and returns the lambda (resulting in a dangling reference after the function returns, and undefined behavior when called).
#include <cstdio>
#include <functional>
std::function<int()> make_counter() {
int count = 10;
return [&count] { return ++count; }; // 지역 변수를 참조로 캡처 -> 함수가 끝나면 댕글링
}
int main() {
auto f = make_counter();
std::printf("%d\n", f()); // 정의되지 않은 동작(UB)
}
Compiling with g++ -std=c++17 -Wall -Wextra -O2 lambda_dangling.cpp prints the following warning excerpt (with ... representing omitted inlining notes):
In lambda function,
...
lambda_dangling.cpp:5:32: warning: ‘count’ is used uninitialized [-Wuninitialized]
Three runs printed 32572, 32608, and 32723 (exit 0). Reading a dangling reference is undefined behavior. The numbers above happened to come out in this environment; with another compiler or other options you may get different values or a crash, or it may even look like it works and prints the right value.
![When a [&count] capture starts dangling: after make_counter() returns the stack slot is gone while the lambda still holds a reference, leading to UB](/_astro/dangling-capture-en.BV6GFQYo_ZYswC.webp)
How do you detect and fix a dangling capture?
One-line answer: Use AddressSanitizer (-fsanitize=address) to catch stack-use-after-return at runtime, and capture by value or with [*this] whenever a lambda outlives its scope.
Building with AddressSanitizer: finding memory errors at runtime (Korean) via g++ -std=c++17 -g -O0 -fsanitize=address lambda_dangling.cpp and running the binary exits with code 1 and prints the following report (PID and addresses masked):
==PID==ERROR: AddressSanitizer: stack-use-after-return on address 0x... at pc 0x... bp 0x... sp 0x...
READ of size 4 at 0x... thread T0
#0 0x... in operator() .../lambda_dangling.cpp:5
...
SUMMARY: AddressSanitizer: stack-use-after-return .../lambda_dangling.cpp:5 in operator()
AddressSanitizer pinpoints the stack-use-after-return at lambda_dangling.cpp:5. To fix it, capture by value so the closure owns its own copy. Here is lambda_fixed.cpp, which compiles without warnings under g++ -std=c++17 -Wall -Wextra (capturing by value so the lambda holds a copy).
#include <cstdio>
#include <functional>
std::function<int()> make_counter() {
int count = 10;
return [count]() mutable { return ++count; }; // 값으로 캡처: 람다가 복사본을 가짐
}
int main() {
auto f = make_counter();
std::printf("%d\n", f());
std::printf("%d\n", f());
}
The output is:
11
12
Two practical rules help prevent dangling captures. First, capture by value whenever the lambda outlives the current scope (such as when returning it, storing it in a container or callback, or passing it to another thread). Second, inside a member function, members are accessed through this: writing [=] implicitly captures *this by reference by copying the this pointer rather than copying the object itself (implicit capture of this via [=] is deprecated since C++20). Use [*this] (introduced in C++17) to capture a copy of the object.
What are the frequently asked questions?
One-line answer: Here are answers on C++14 init capture for move-only types, why [=] can still dangle with pointers or this, and capturing smart pointers.
How do you move-capture an object into a lambda?
Use C++14 init capture such as [v = std::move(v)] to capture move-only types (this one-line syntax snippet is not a separately run program). For the difference between copying and moving, see Copy Constructor vs Move Constructor in C++: Which One Is Called, and When?.
Is capturing with [=] always safe from dangling?
No. If you capture a raw pointer by copy, only the pointer value is copied, so it still dangles if the pointee is destroyed; likewise, inside a member function, [=] copies the this pointer rather than the object, so *this dangles if the object’s lifetime ends.
What happens when you capture a smart pointer?
Copying a std::shared_ptr into a lambda keeps the reference count and the managed object alive for as long as the closure exists (see C++ unique_ptr and shared_ptr, how to choose in interviews (Korean)).
What related posts are worth reading?
One-line answer: Related posts covering C++ Insights, AddressSanitizer, smart pointers, and copy vs move constructors.
- What Is C++ Insights? How to See the Code Your Compiler Hides (Lambdas, Range-for)
- AddressSanitizer: how to find memory errors at runtime (Korean)
- C++ unique_ptr vs shared_ptr: criteria for choosing (Korean)
- Copy Constructor vs Move Constructor in C++: Which One Is Called, and When?
What are the sources?
One-line answer: The cppreference Lambda expressions documentation and our GCC 14.2.0 test environment.
- cppreference.com, “Lambda expressions” (checked 2026-10-25)
- Compiler and environment:
g++ (Debian 14.2.0-19) 14.2.0,x86_64(checked 2026-10-25)