Exactly where is the machine code for a lambda stored, if the lambda takes an argument of auto
type?
Details follow.
Lambdas are compiled at compile time, are they not? As far as I know, compilation requires that types be known at compile time.
But if so, then how is this MCVE possible?
#include <typeinfo>
#include <iostream>
namespace My {
struct S {};
}
int main()
{
auto n = 42;
// An object n exists on the stack.
auto f = [](const auto n) {return n;};
// The f resembles a template. Does an object f exist on the stack?
const std::type_info& ti1 {typeid(f)};
const std::type_info& ti2 {typeid(f(My::S {}))};
std::cout
<< &n << " "
<< n << " "
<< &f << " " // If f is no object then why does this work?
<< ti1.name() << " "
<< ti2.name() << "\n";
return 0;
}
Output (demangled): 0x7ffd6a22b41c 42 0x7ffd6a22b41b main::{lambda(auto:1)#1} My::S
Does this imply that no object f
, except perhaps for a placeholder, exists on the stack? But if so, then f
is not an object but merely a template, is it not?
I am confused. If you can, please explain what kind of compile-time/run-time object a lambda like f
is, how the compiler treats it, where it exists at run time, roughly how it could be laid out on the stack, and so on. Even a partial answer would be appreciated.
(I observe, incidentally, based on addresses output, that f
—or the placeholder for f
—seems to occupy exactly one byte at run time, but do not know what sense to make of this observation. Note that a C++14 or later compiler is required, for C++11 cannot handle such template-like lambdas.)
Related:
- What is a lambda expression in C++11? (The present question however regards C++14 and later.)
- How can I return a lambda object?