1

Question is why program print id:0, id:1, id:2, 42 instead of id:42, id:43, id:44, 45.

int main()
{

    int id = 0;
    auto f = [id] () mutable {
        std::cout << "id: " << id << std::endl;
        ++id; // OK
    };

    id = 42;
    f();
    f();
    f();
    std::cout << id << std::endl;
    return 0;
}
1
  • Are you asking why it is specified to do this? Commented Sep 13, 2018 at 6:39

1 Answer 1

8

Because id is captured by value, i.e. it gets copied. And when the lambda is declared (i.e. when capture happens) id has the value of 0.

You might want to change it to capture-by-reference.

auto f = [&id] () {
//        ^
    std::cout << "id: " << id << std::endl;
    ++id;
};

BTW: For this case mutable becomes superfluous.

LIVE

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.