1

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.

5
  • Nothing wrong with the recursion but why are you capturing the lambda by reference? Commented Apr 6, 2012 at 16:08
  • 1
    @JaredPar otherwise it crashes in msvc2010 compiler :) Commented Apr 6, 2012 at 16:14
  • 3
    @JaredPar: because if he captured it by value, he'd get a copy of the function object when the lambda was created, BEFORE f was initialized? Undefined behavior Commented Apr 6, 2012 at 16:16
  • @Xeo: I think the question is different enough to stand on its own. It's asking about whether this is legal C++11 code; that question is about the use of auto funcname rather than std::function<> funcname. Commented Apr 6, 2012 at 16:29
  • 1
    @Nicol: Yep, noticed that after my vote though... I deleted the comment so it wouldn't encourage other close votes. My bad. Commented Apr 6, 2012 at 16:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.