innochenti
innochenti

Reputation: 1103

recursive lambda via reference

Is this code correct?

std::function<int(int)> f = [&f](int n) -> int
{
    return n <= 1 ? 1 : n * f(n - 1);
};

int x = f(42);

Is there any potential problem with object construction before it passed as reference to lambda? Or this code absolutely correct?

Capturing f by value leads to crash in msvc2010 compiler.

Upvotes: 1

Views: 265

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474076

This should work fine, so long as you follow the rules of references to stack variables stored in lambdas. It is well-defined C++11 code.

Upvotes: 1

Related Questions