When a C++ lambda expression has a lot of captures by reference, the size of the unnamed function object becomes large

后端 未结 3 709
野趣味
野趣味 2020-12-11 18:39

The following code:

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


        
3条回答
  •  没有蜡笔的小新
    2020-12-11 18:47

    I do not understand why you seem surprised.

    The C++ Standard gives a set of requirements, and every single implementation is free to pick any strategy that meets the requirements.

    Why would an implementation optimize the size of the lambda object ?

    Specifically, do you realize how that would tie down the generated code of this lambda to the generated code for the surrounding function ?

    It's easy to say Hey! This could be optimized!, but it's much more difficult to actually optimize and make sure it works in all edge cases. So, personally, I much prefer having a simple and working implementation than a botched attempt at optimizing it...

    ... especially when the work-around is so easy:

    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;
    }
    

    Look Ma: 4 bytes only!

提交回复
热议问题