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 this by value

Use case

Safe callbacks that outlive the object.

Explanation

[*this] captures a copy of the object. Safe even after the original object is destroyed.

Code

#include <cstdint>
#include <functional>
#include <iostream>

struct Analyzer {
  uint64_t baseAddr = 0x10000000;

  auto getCallback() {
    return [*this]() { return baseAddr; };
  }
};

int main() {
  std::function<uint64_t()> callback;

  {
    Analyzer a;
    callback = a.getCallback();
    a.baseAddr = 0xDEAD;
  }

  std::cout << "Base: 0x" << std::hex << callback() << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/lambda-capture-this-by-value
Base: 0x10000000