fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4.  
  5. class OtherThing{
  6. public:
  7. void addElement(std::function<int()> func){
  8. this->myfuncs.push_back(func);
  9. }
  10. void toggle(){
  11. std::cout << "toggle .. " << this->myfuncs[0]() << std::endl;
  12. }
  13. private:
  14. std::vector<std::function<int()>> myfuncs;
  15. };
  16.  
  17. class Thing: public OtherThing{
  18. public:
  19. Thing(){
  20. std::function<int()> myfunc= [this]()->int{
  21. std::cout << "from lambda " << this->value << std::endl;
  22. return this->value;
  23. };
  24. this->addElement(myfunc);
  25. }
  26. Thing(const Thing &src){
  27. value = src.value;
  28. std::function<int()> myfunc = [this]()->int{
  29. std::cout << "from copied lambda " << this->value << std::endl;
  30. return this->value;
  31. };
  32. this->addElement(myfunc);
  33. }
  34. void setValue(int value){
  35. this->value = value;
  36. }
  37. int getValue(){
  38. return this->value;
  39. }
  40. private:
  41. int value;
  42. };
  43.  
  44.  
  45. int main() {
  46. // container for things
  47. std::vector<Thing> mythings;
  48.  
  49. // a thing
  50. Thing a;
  51. a.toggle();
  52. a.setValue(100);
  53. a.toggle();
  54.  
  55. mythings.push_back(a);
  56. mythings[0].toggle();
  57. mythings[0].setValue(666);
  58. mythings[0].toggle();
  59. mythings[0].setValue(999);
  60. mythings[0].toggle();
  61.  
  62. a.toggle();
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 5524KB
stdin
Standard input is empty
stdout
toggle .. from lambda 1727656200
1727656200
toggle .. from lambda 100
100
toggle .. from copied lambda 100
100
toggle .. from copied lambda 666
666
toggle .. from copied lambda 999
999
toggle .. from lambda 100
100