mercredi 6 septembre 2017

Segmentation fault with std::function and lambda parameters

Can you please explain why this code crashes? I would expect output of "a", but I get segmentation fault.

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


using namespace std;

struct MyStruct {
  vector<string> a;
  vector<string> b;
};

void out_data(const MyStruct& my_struct, const std::function<const vector<string>&(const MyStruct&)> getter) {
  cout << getter(my_struct)[0] << endl;
}

int main(int argc, char** argv)
{
  MyStruct my_struct;
  my_struct.a.push_back("a");
  my_struct.b.push_back("b");
  out_data(my_struct, [](const MyStruct& in) {return in.a;});
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire