1

If i assign value with call fun1() the x variable outside lambda will be broken (unable to read memory), but if I run fun2() everything is good. Why? Copy of pointer still points to the same thing right? Then why does fun1() does not work?

int *x = NULL;
    auto fun1 = [x]() mutable
    {
        x = new int(5);
    };
    auto fun2 = [&x]()
    {
        x = new int(5);
    };
4
  • the first captures by copy Commented Aug 22, 2014 at 9:49
  • This has nothing to do with lambdas. Try with a plain old function and see. Commented Aug 22, 2014 at 9:49
  • So why copy of pointer does not point to the same thing? Commented Aug 22, 2014 at 9:51
  • Because it is a local copy of a pointer. Commented Aug 22, 2014 at 9:51

2 Answers 2

2
auto fun1 = [x]() mutable { ... }

Captures x by copy, so it modifies a copy of x. When the lamdba returns, your x is still not assigned.

auto fun2 = [&x]() { ... }

Captures x by reference, so you really are modifying x.

This is not related to lambdas : the same behavior exists with regular functions (see value and reference semantics entry in the C++ FAQ)

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

Comments

1

I think the user is getting confused here because it is a pointer, but pointers are variables too and can also be passed by value or by reference.

Here it is x itself, not where x points that is crucial. You need to modify the pointer, not where it points. Therefore you have to pass it to the lambda by reference.

If what you were interested in was *x in reality, and x itself is not going to be modified (to point elsewhere) then you would simply pass it to the lambda by value, just like you'd pass it to a function by value.

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.