Figuring out why capturing by reference in a nested lambda produces a weird result

  c++, lambda

When the outer variable x is captured by value

return [=](int y){ return x * y; };

foo(2)(3) produces 6.

However if I capture x by reference

return [&](int y){ return x * y; };

foo(2)(3) produces 9.

Minimal Code

#include <iostream>
#include <functional>

int main()
{
    using namespace std;
    function<function<int(int)>(int)> foo = [](int x)
    {
        return [&](int y) { return x * y; };
    };
    cout << foo(2)(3);
    return 0;
}

Question

I cannot figure out why this happens, can you?

Source: Windows Questions C++

LEAVE A COMMENT