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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With