c++ - how can static variables be directly used in lambda's body even the invoking beyond the scope of the static variables -
i'm getting confused when reading capture rule of local static variables lambda, see below codes:
std::function<bool(int)> returnlambda() { static int s_b = 1; homecoming [](int a){return a+s_b ;} ; } int main() { int i; = returnlambda()(2); homecoming i; } in returnlambda function, when lambda look envaluated, 1 function object constructed , returned.then there 1 re-create @ invoking place, , operator() invoked @ invoking place, local static variable. here question is, why local static variable within returnlambda function can still live outside returnlambda function? can not refer 1 local static variables outsie it's sope.
the rules lambdas state can't utilize captured entity beyond lifetime of said entity.
the lifetime of object static lifetime until end of main() (or phone call exit()). there's no problem using after returning lambda. usage in destructors of other objects static lifetime (e.g. globals) problem.
in fact, variable isn't captured lambda. no need, there no need capture global variable. works because identifier lookup within lambda finds object static lifetime in enclosing scope, gets used. because variable not have automatic storage duration, rule implicit capture isn't triggered.
this rule, 5.1.2:
a lambda-expression associated capture-default not explicitly capture this or variable automatic storage duration (this excludes id-expression has been found refer init-capture's associated non-static info member), said implicitly capture entity (i.e., this or variable) if compound-statement:
the whole reason capture machinery lambda can locate variables uses, if variables have time-varying location. static variables (and globals, , static class members, , functions, , whatever else isn't automatic local variable or non-static info fellow member of this) don't move around, sticking location in lambda object isn't necessary.
in short: absolutely can go on using static locals outside scope. many standard library functions work way, illustration asctime. scope determines whether name recognized; objects static or dynamic lifetime, scope has no effect on lifetime.
c++ lambda
No comments:
Post a Comment