Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 743
hovnatan Avatar asked Sep 06 '17 11:09

hovnatan


1 Answers

The

[](const MyStruct& in) {return in.a;}

lambda expression is equivalent to

[](const MyStruct& in) -> auto {return in.a;}

which returns a copy of in.a. Your std::function signature then returns a dangling reference to a local object.


Change the lambda expression to

[](const MyStruct& in) -> const auto& {return in.a;}

to return a const& instead, fixing the segfault.


Also, don't use std::function to pass lambdas unless you have a good reason to do so. I suggest reading my article on the subject: "passing functions to functions".

like image 88
Vittorio Romeo Avatar answered Sep 19 '22 11:09

Vittorio Romeo