dimanche 31 janvier 2016

C++ Lambda stored in container capturing "this"

Consider the following minimal code:

#include <functional>
#include <iostream>
#include <string>
#include <vector>

class A
{
public:
  A() :
    s("dummy"),
    f([&, this]{ return s == "dummy"; }),
  {}
  std::string s;
  std::function<bool ()> f;
};

int main(int argc, char *argv[])
{
  A a;
  a.f(); // seems fine

  std::vector<A> as({});
  as[0].f(); // segmentation fault
}

Class A has a lambda member that captures this pointer. When running the code above, lambda works fine when invoked from standalone A instance, but I get segmentation fault when called from an instance stored in the vector.

Why does it happen?

Aucun commentaire:

Enregistrer un commentaire