以下编译正常,N在 lambda fn(C++17) 中隐式捕获:
void f()
{
const int N{42};
auto fn = []() { return N; };
}
Run Code Online (Sandbox Code Playgroud)
( https://godbolt.org/z/JpyZHC )
以下内容无法编译(delay未捕获),我很难弄清楚确切原因是什么。因为delay不是POD?阅读 cppreference.com 后,它似乎与 ODR 使用有关,但我无法理解ODR 使用方面N和之间的显着区别delay。更改const为constexpr下面没有任何区别。
#include <chrono>
#include <thread>
void g()
{
using namespace std::chrono_literals;
const auto delay{42ms};
auto fn = []() { std::this_thread::sleep_for(delay); };
}
Run Code Online (Sandbox Code Playgroud)
std::this_thread::sleep_for通过引用获取它的参数。这意味着它需要 ODR 使用delay并且需要 lambda 捕获delay.
在您的第一个示例中,您不使用 ODR,N因此不需要捕获它。