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

Deprecate implicit capture of this

Use case

Avoid dangling pointer bugs with lambdas.

Explanation

[=] captures this by pointer. Object dies –> dangling pointer. C++20 requires explicit this or *this.

Code

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

struct Analyzer {
  uint64_t base = 0x10000000;

  // implicit capture of 'this' with a capture default of '=' is deprecated
  // auto getBadLogger() {
  //   return [=]() { return base; };
  // }

  auto getGoodLogger() {
    return [=, this]() { return base; };
  }

  // Copy of *this.
  // Safe if object dies.
  auto getSafeLogger() {
    return [=, *this]() { return base; };
  }
};

int main() {
  auto goodLogger = Analyzer{}.getGoodLogger();
  std::cout << "Base: 0x" << std::hex << goodLogger() << "\n";
  auto safeLogger = Analyzer{}.getSafeLogger();
  std::cout << "Base: 0x" << std::hex << safeLogger() << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/deprecate-implicit-capture-of-this
Base: 0x10000000
Base: 0x10000000