Back to results for “Lambda Expressions”
C++ › Lambda Expressions

What is capturing by move (init capture) and when is it needed?

Advanced

Answer

C++14 init captures allow initializing a capture with an expression, including moving a move-only object into the closure: [p = std::move(ptr)]. This is needed to capture things like unique_ptr, which can't be copied, so the lambda takes ownership. It also lets you compute or rename captured values.
auto up = std::make_unique<int>(5);
auto f = [p = std::move(up)]() { return *p; }; // owns the unique_ptr
Real-world example A task lambda takes ownership of a unique_ptr resource via move capture so it can run on another thread.

Common follow-ups: Why can't you capture unique_ptr by value normally? | What else can init capture do?