Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes the following difference in implicit lambda capture behavior?

Tags:

c++

lambda

c++17

The following compiles fine, N is implicitly captured in the lambda fn (C++17):

void f()
{ 
  const int N{42};
  auto fn = []() { return N; };
}

(https://godbolt.org/z/JpyZHC)

The following does not compile (delay is not captured), and I have a hard time figuring out what the exact reason is. Because delay is not a POD? After reading cppreference.com it seems it has something to do with ODR-usage, but I fail to grasp what the significant difference between N and delay is in terms of ODR-usage. Changing const to constexpr below does not make a difference.

#include <chrono>
#include <thread>

void g()
{
  using namespace std::chrono_literals; 
  const auto delay{42ms};
  auto fn = []() { std::this_thread::sleep_for(delay); };
}

(https://godbolt.org/z/XA3WCR)

like image 505
Ton van den Heuvel Avatar asked May 19 '20 15:05

Ton van den Heuvel


1 Answers

std::this_thread::sleep_for takes it's parameter by reference. This means that it needs to ODR-use delay and that requires that the lambda capture delay.

In your first example you do not ODR-use N so it's not required that it be captured.

like image 61
NathanOliver Avatar answered Sep 22 '22 16:09

NathanOliver