fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <functional>
  4.  
  5. class Foo
  6. {
  7. public:
  8.  
  9. Foo () = default;
  10. ~Foo () = default;
  11.  
  12. void set (const std::string & v)
  13. {
  14. value = v;
  15. }
  16.  
  17. void set ()
  18. {
  19. lambda = [](Foo* self)
  20. {
  21. return self->value;
  22. };
  23. }
  24.  
  25. std::string get ()
  26. {
  27. return lambda(this);
  28. }
  29.  
  30.  
  31. std::string value;
  32. std::function <std::string (Foo*)> lambda;
  33. };
  34.  
  35. int main ()
  36. {
  37. Foo foo;
  38.  
  39. foo.set ();
  40. foo.set ("first");
  41.  
  42. std::cerr << foo.get () << std::endl; // prints "first"
  43.  
  44. foo.set ("captures change");
  45.  
  46. std::cerr << foo.get () << std::endl; // prints "captures change"
  47.  
  48. Foo foo2 (foo);
  49. foo2.set ("second");
  50.  
  51. std::cerr << foo.get () << std::endl; // prints "captures change" (as desired)
  52. std::cerr << foo2.get () << std::endl; // prints "captures change" (I would want "second" here)
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 3060KB
stdin
Standard input is empty
stdout
Standard output is empty