Why is a captureless lambda convertible to a function pointer?
C++Level: IntermediateModern C++ Features
Why is a captureless lambda convertible to a function pointer?
Hints
- Who owns the resource and when does its lifetime end?
- Check copying, moving, exceptions and use after release.
Answer
Captureless Lambdas and Function Pointers
:Source: src/lambda/captureless
Lambdas without captures can implicitly convert to function pointers, making them compatible with C APIs and legacy code expecting function pointers. This conversion is only possible when the lambda captures nothing, as captured variables require storage that function pointers cannot provide.
#include <iostream>
int main() {
// Captureless lambda converts to function pointer
long (*fib)(long) = [](long n) {
long a = 0, b = 1;
for (long i = 0; i < n; ++i) {
long tmp = b;
b = a + b;
a = tmp;
}
return a;
};
std::cout << fib(10) << "\n"; // Output: 55
}
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT