I am running the below code and I am getting unexpected results:
int main()
{
int val = 10;
auto a = [&]() {return val + 53;};
std::cout << sizeof(a) << std::endl; //OUTPUTS 8
}
I got to know that lambdas basically decompose to functors. So I thought sizeof for a should return 4 (size of member variable reference for val). But this is not the case.
I tried cpp insights to see if there is additional member variables, but I could only find the member variable reference for val. a is being expanded to anonymous class
Am I missing something here?
>Solution :
If we replace the lambda with an actual functor you’ll see the same result:
#include <iostream>
struct Lambda
{
int & val;
int operator()()
{
return val + 53;
}
};
int main()
{
int val = 10;
auto a = Lambda{val};
std::cout << sizeof(a) << std::endl; //OUTPUTS 8
}
The lambda is storing a reference, not the value. References are usually the same size as a pointer so will normally be 8 bytes on a 64-bit platform.
If we capture by value the size is 4 as you expect:
#include <iostream>
struct Lambda
{
int val;
int operator()()
{
return val + 53;
}
};
int main()
{
int val = 10;
auto a = Lambda{val};
std::cout << sizeof(a) << std::endl;
}