C ++ 11: will lambda malloc space every time it is declared?

Just want to clear it up: will lambda malloc space every time and free up when the block ends? eg

void func() {
    auto lambda = [] (args) { expressions; }
    static auto s_lambda = [] (args) { expressions; }
}

      

where lambda () will be malloc-ed for ram every time I call func () and s_lamda () won't?

In this case, the performance of lambda () will be slightly worse than s_lambda () if they have a really huge func body?

+3


source to share


1 answer


The lambda object will take up memory, but not in the way you think.

auto lambda = [] (args) { expressions; }

      

translated by the compiler to something like (very simplistic)



struct __lambda {
    auto operator()(args) { expressions; }
};

__lambda lambda;

      

Because of the way C ++ works, every object is strictly positive, and sizeof(lambda)

will be at least one. Depending on what your lambdas are being captured, those captures may be stored as fields in a compiler-generated class, in which case the lambda will take up more memory to store these snapshots.

But the actual body of the inner function operator()

is what is compiled, it is not what is generated at runtime over and over and over. And if your lambda doesn't actually use the captured data, storing at least one byte is likely to be optimized.

+6


source







All Articles