Quaxton Hale
Quaxton Hale

Reputation: 2520

Lambda function - capturing by value

Why does this result in a segmentation fault?

#include <iostream>
#include <functional>
using namespace std;

int main() {

     function<int(int,int)> hcf = [=](int m, int n)mutable->int{
    // cout << "m: " << m << " n: " << n << endl;
    if(m<n) return hcf(n,m);
    int remainder(m%n);
    if(0 == remainder) return n;
    return hcf(n,remainder);
};

    cout << hcf(10,15) << endl;

    return 0;
}

I have added the mutable keyword. Shouldn't pass-by-value work? Why does this require pass-by-reference? Is it because I am calling hcf recursively?

Upvotes: 1

Views: 131

Answers (1)

Columbo
Columbo

Reputation: 60979

The closure object is initialized before hcf as it is hcf's initializer. Even if your code wouldn't invoke UB you would still copy hcfs still empty state into the member variable of the closure object. Subsequently calling it would then result in calling an empty function.

When you capture by reference this isn't a problem anymore as with the references first use (that is, the first call to the closure object), hcf has already been properly initialized.

Upvotes: 5

Related Questions