#include <iostream>
#include <string>
#include <functional>
class Foo
{
public:
Foo () = default;
~Foo () = default;
void set (const std::string & v)
{
value = v;
}
void set ()
{
lambda = [](Foo* self)
{
return self->value;
};
}
std::string get ()
{
return lambda(this);
}
std::string value;
std::function <std::string (Foo*)> 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;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgojaW5jbHVkZSA8ZnVuY3Rpb25hbD4KCmNsYXNzIEZvbwp7CiAgcHVibGljOgoKICAgIEZvbyAoKSA9IGRlZmF1bHQ7CiAgICB+Rm9vICgpID0gZGVmYXVsdDsKCiAgICB2b2lkIHNldCAoY29uc3Qgc3RkOjpzdHJpbmcgJiB2KQogICAgewogICAgICAgIHZhbHVlID0gdjsKICAgIH0KCiAgICB2b2lkIHNldCAoKQogICAgewogICAgICAgIGxhbWJkYSA9IFtdKEZvbyogc2VsZikKICAgICAgICB7CiAgICAgICAgICAgIHJldHVybiBzZWxmLT52YWx1ZTsKICAgICAgICB9OwogICAgfQoKICAgIHN0ZDo6c3RyaW5nIGdldCAoKQogICAgewogICAgICAgIHJldHVybiBsYW1iZGEodGhpcyk7CiAgICB9CgoKICAgIHN0ZDo6c3RyaW5nIHZhbHVlOwogICAgc3RkOjpmdW5jdGlvbiA8c3RkOjpzdHJpbmcgKEZvbyopPiBsYW1iZGE7Cn07CgppbnQgbWFpbiAoKQp7CiAgICBGb28gZm9vOwoKICAgIGZvby5zZXQgKCk7CiAgICBmb28uc2V0ICgiZmlyc3QiKTsKCiAgICBzdGQ6OmNlcnIgPDwgZm9vLmdldCAoKSA8PCBzdGQ6OmVuZGw7IC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