mercredi 31 décembre 2014

C++11: track object lifetime in lambda

Sometimes, we know nothing about lifetime of lambda that captures an object state (e.g. return it from object, register it as a callback without ability to unsubscribe etc.). How to make sure that the lambda won't access already destroyed object on invocation?



#include <iostream>
#include <memory>
#include <string>

class Foo {
public:
Foo(const std::string& i_name) : name(i_name) {}

std::function<void()> GetPrinter() {
return [this]() {
std::cout << name << std::endl;
};
}

std::string name;
};

int main() {
std::function<void()> f;

{
auto foo = std::make_shared<Foo>("OK");
f = foo->GetPrinter();
}

auto foo = std::make_shared<Foo>("WRONG");

f();

return 0;
}


This program prints "WRONG" instead of "OK" (http://ideone.com/Srp7RC) just by coincidence (it seems it just reused the same memory for the second Foo object). Anyway, this is a wrong program. First Foo object is already dead when we execute f.


Aucun commentaire:

Enregistrer un commentaire