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;
}
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With