shaz shaz - 3 months ago 7
C++ Question

c++ std::function returns unexpected value

#include <iostream>

typedef std::function<bool(int)> set;

using namespace std;

set singletonSet(int a) {
return [&] (int x) { return (a == x); };
}

bool contains(set s, int test) {
return s(test);
}


int main() {
auto first = singletonSet(5);

auto r1 = contains(first, 10);
auto r2 = contains(first, 5);

cout << r1 << " " << r2 << endl;

return 0;
}


I expect this to print
0 1
but result is
1 1


Beginner c++ labmda programmer here so sorry in advance if this is a basic error.

Answer

Don't capture a by reference, capture it by value. As-is, you're storing a dangling reference inside the lambda, and using it later leads to UB.

set singletonSet(int a) {
    return [=] (int x) { return (a == x); };
    //      ^
}
Comments