简体   繁体   中英

is variable capture in lambda functions which are members of a static data structure allowed?

I got the following code snipped.

bool parseTool() {
   string name;
   string version;
   static /*!!*/ AttrMap attrMap = {
       {"name", Attr([&](const string &val)->bool{name = val;return true;})},
       {"version", Attr([&](const string &val)->bool{version = val;return true;})},
   };
   return parseAttributes(attrMap);
}

The attrMap is declared static and lambda functions capture variables from the stack of the parseTool.

Compilation produces no errors and executable runs happily, up to some point, when it starts producing trash. Of course, removing 'static' fixes the 'trash' issue (probably making name and version static will fix it too, but i have not tried it). I do not understand what does compiler capture in this case when the static attrMap is initialized.

The question is, why did not compiler complain about it? Is there anything in the standard which would mark this case (I could not find one)? What does compiler do there?

I was running gcc-7.2.8 with -std=c++17 on linux.

The compiler has no way of knowing that the references you are capturing will no longer be valid the next time the lambda is called or even if the lamda will ever be called again.

The code you have posted is dangerous and likely to fail but is perfectly valid according to the standard so the compiler is free to accept it without warnings.

To fix it capture the variables by value or make the lambda not static. Making the lambda static probably doesn't make much sense as creating a lambda probably isn't expensive in most implementations and depending how the lambda is used may be inlined away completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM