Advertisement
Advanced C++, Lambda Expressions

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

Short 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.

Save C++ mock interview
Advertisement
AModel 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.
Likely follow-ups
  • Why can't you capture unique_ptr by value normally? | What else can init capture do?
Related topics