Li Chen
Li Chen

Reputation: 5270

different output when I use lambda which return lambda too in c++?

# pass by value
    #include "stdafx.h"
    #include <functional>
    #include <iostream>
    #include <string>
    std::function<void(int)> Foo(int v)
    {
        auto l = [v](int i)
        {
            std::cout << v << " " << i << std::endl;
        };
        return l;
    }

    int main()
    {
        //[](int e, int f) {std::cout << e << f; }(5, 6);
        [](int a, int b)
        {
            return [=](int c, int d)
            {
                int a1 = a, a2 = b, a3 = c, a4 = d;
                std::cout << a << " " << b << std::endl << c << " " << d << std::endl;
            };
        }(2, 3)(4, 5);
    }

enter image description here


# pass by reference
    #include "stdafx.h"
    #include <functional>
    #include <iostream>
    #include <string>
    std::function<void(int)> Foo(int v)
    {
        auto l = [v](int i)
        {
            std::cout << v << " " << i << std::endl;
        };
        return l;
    }

    int main()
    {
        //[](int e, int f) {std::cout << e << f; }(5, 6);
        [](int a, int b)
        {
            return [&](int c, int d)
            {
                int a1 = a, a2 = b, a3 = c, a4 = d;
                std::cout << a << " " << b << std::endl << c << " " << d << std::endl;
            };
        }(2, 3)(4, 5);
    }

enter image description here

my question is when I pass references, why the output is not the same as passing values? mingw also has different values with reference-passing: 4 5 4 5 when I learn the little schemer, I try convert codes in the book to c++, then come up with the question.

Upvotes: 0

Views: 41

Answers (1)

yuri kilochek
yuri kilochek

Reputation: 13486

a and b are dangling references at the point of call.

Upvotes: 3

Related Questions