c++ - Share variable between two lambdas -
i want able share variable in containing scope between 2 lambda functions. have following:
void holdadd(const rect& rectangle, hold anonymousheld, hold anonymousfinish) { std::map<int,bool> identifiercollection; holdfinish holdfinish = [=](const int& identifier) mutable { if (identifiercollection.count(identifier) == 0) return; identifiercollection.erase(identifier); anonymousfinish(); }; holdcollisioncollection.push_back([=](const int& identifier, const vec2& point) mutable { if (rectangle.containspoint(point)) { identifiercollection[identifier] = true; anonymousheld(); } else { holdfinish(identifier); } }); holdfinishcollection.push_back(holdfinish); }
i can see in debugger holdfinish
pointing different implementation of identifiercollection
in 2nd lambda function.
if use [=, &identifiercollection]
throws exc_bad_access
whether use mutable
or not.
my experience other languages implement inline functions should possible. instance in javascript:
var = 10; var b = function() { += 2; } var c = function() { += 3; } b(); c(); alert(a);
would alert 15
.
what have both lambda functions reference same identifiercollection implementation? behaves in same way javascript example.
unlike in scripting languages, identifiercollection
's lifetime won't extended because captured closure. change [=]
[&]
capture reference, it's dangling reference local variable you're capturing.
you'll have manage lifetime of identifiercollection
yourself; frankly, sounds perfect opportunity shared pointer, captured value each lambda. dynamically-allocated map wraps literally exist long need to.
void holdadd(const rect& rectangle, hold anonymousheld, hold anonymousfinish) { auto identifiercollection = std::make_shared<std::map<int,bool>>(); holdfinish holdfinish = [=](const int& identifier) mutable { if (identifiercollection->count(identifier) == 0) return; identifiercollection->erase(identifier); anonymousfinish(); }; holdcollisioncollection.push_back([=](const int& identifier, const vec2& point) mutable { if (rectangle.containspoint(point)) { (*identifiercollection)[identifier] = true; anonymousheld(); } else { holdfinish(identifier); } }); holdfinishcollection.push_back(holdfinish); }
Comments
Post a Comment