Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected sizeof auto variable assigned to lambda

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
  
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading