I have a situation where I have a lambda as a member variable that is created by a specific function call. The problem is that he captures this as part of his work. Later, I want to be able to copy the entire object ...
However, during copying, I do not know how the lambda was created (it could be defined at several points through different code paths). Therefore, I do not understand a little what to add to the copy constructor. Ideally, I would like to "reconfirm" the lambda bindings to the newly created "this".
Is it possible?
Here is a sample code:
#include <iostream> #include <string> #include <functional> class Foo { public: Foo () = default; ~Foo () = default; void set (const std::string & v) { value = v; } void set () { lambda = [&]() { return this->value; }; } std::string get () { return lambda(); } std::string value; std::function <std::string (void)> lambda; }; int main () { Foo foo; foo.set (); foo.set ("first"); std::cerr << foo.get () << std::endl; // prints "first" foo.set ("captures change"); std::cerr << foo.get () << std::endl; // prints "captures change" Foo foo2 (foo); foo2.set ("second"); std::cerr << foo.get () << std::endl; // prints "captures change" (as desired) std::cerr << foo2.get () << std::endl; // prints "captures change" (I would want "second" here) return 0; }
Thanks in advance.
source share