When a C ++ lambda expression has many records by reference, the size of an object with an unnamed function becomes large

The following code:

int main() {
    int a, b, c, d, e, f, g;
    auto func = [&](){cout << a << b << c << d << e << f << g << endl;};
    cout << sizeof(func) << endl;
    return 0;
}

outputs 56 compiled with g ++ 4.8.2

Since all local variables are stored in the same stack stack, remembering one pointer is enough to find the addresses of all local variables. Why does a lambda expression build such a large unnamed function object?

+4
source share
3 answers

I do not understand why you are surprised.

The C ++ standard provides a set of requirements, and each individual implementation can choose any strategy that meets the requirements.

Why does the implementation optimize the size of the lambda object?

, , ?

, ! !, , . , ...

... , :

struct S { int a, b, c, d, e, f, g; };

int main() {
    S s = {};
    auto func = [&](){
        std::cout << s.a << s.b << s.c << s.d << s.e << s.f << s.g << "\n";
    };
    std::cout << sizeof(func) << "\n";
    return 0;
}

: 4 !

+4

. ( , ).

++ -, , , , .

, , , " " ++-. this, , - bog-standard operator(). " " ++- , " " ..

-, , , . ( ), . , , , , , .

- . , void*, . , , ( undefined). , , ( , , ) lambdas .

. , , . , , . , , .

, .

+2

. , , , , , - .

There would be nothing wrong with compiling one pointer and using offsets to do what you propose as an optimization. Perhaps some compilers do this, I don't know.

+1
source

Source: https://habr.com/ru/post/1537058/


All Articles