c++ - struct containing lambdas which modify values via reference -
here's simple program uses value_control
struct store lambdas modify integer variable:
#include <iostream> #include <functional> struct value_control { std::function<void(void)> increase; std::function<void(void)> decrease; }; int main() { auto = 123; value_control a_control{ [&]() { += 1; }, [&]() { -= 1; } }; a_control.decrease(); std::cout << << std::endl; a_control.increase(); std::cout << << std::endl; }
output:
122 123
here's version abstracts out value_control
creation make_numeric_control
:
#include <iostream> #include <functional> struct value_control { std::function<void(void)> increase; std::function<void(void)> decrease; }; int main() { auto make_numeric_control = [](int& var, int change) { return value_control { [&]() { var += change; }, [&]() { var -= change; } }; }; auto = 123; auto a_control = make_numeric_control(a, 1); a_control.decrease(); std::cout << << std::endl; a_control.increase(); std::cout << << std::endl; }
this version of program not behave first:
-19620773 178
any suggestions how write make_numeric_control
such second version works first version?
this because capture change
reference var
due [&]
capture specifier. change
destructed when make_numeric_control
exits, inside closure dangling reference.
you can fix capturing var
reference , change
value:
return value_control { [&var, change]() { var += change; }, [&var, change]() { var -= change; } };
Comments
Post a Comment