Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lambda capture initializers

Use case

Move unique_ptr into a lambda for async analysis.

Explanation

[x = expr] initializes a capture with any expression. Enables moving unique_ptr into lambdas and creating computed captures.

Code

#include <cstdint>
#include <iostream>
#include <memory>
#include <vector>

struct AnalysisResult {
  uint64_t entryPoint;
  AnalysisResult(uint64_t e) : entryPoint(e) {}
};

int main() {
  auto result = std::make_unique<AnalysisResult>(0x10001000);

  auto task = [r = std::move(result)]() {
    std::cout << "Entry: 0x" << std::hex << r->entryPoint << "\n";
  };

  std::cout << "Original moved: " << std::boolalpha << (result == nullptr)
            << "\n";

  task();

  int multiplier = 4;
  auto getSize = [pageSize = 4096 * multiplier]() { return pageSize; };

  std::cout << "Size: " << std::dec << getSize() << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++14/build/lambda-capture-initializers
Original moved: true
Entry: 0x10001000
Size: 16384