C ++ lambda function access write violation

I am learning how to use C ++ lambda functions with a class <functional> function. I am trying to solve this Code Golf as a practice (challenge - Curry for Dinner)

I have this function:

// This creates a function that runs y a number of 
// times equal to x return value.
function<void()> Curry(function<int()> x, function<void()> y)
{
    return [&]() {
        for (int i = 0; i < x(); i++)
        {
            y();
        }
    };
}

To test this, I have this code in my main ():

auto x = [](){ return 8; };
auto y = [](){ cout << "test "; };
auto g = Curry(x, y);

It throws Access violation reading location 0xCCCCCCCC.in Functional.h.

However, when I copy-paste the lambda function from inside Curry () inside my main type:

auto x = [](){ return 8; };
auto y = [](){ cout << "test "; };
auto g = [&]() {
    for (int i = 0; i < x(); i++)
    {
        y();
    }
};

I get the code as expected. Why is this happening?

+4
source share
1 answer

You have a few issues.

Here:

  return [&]() {

. , , , . , undefined , . , , , . (. , - - , [&] , , , & [&] . ... , ( [&] lambdas 1 (!)), ++, ...)

  return [=]() {

.

:

  return [x,y]() {

.

, , [&]. , , .

:

    for (int i = 0; i < x(); i++)

x . !

    auto max = x();
    for (auto i = max; i > 0; --i)

max , , , , x unsigned int - .

:

    int max = x();
    for (int i = 0; i < max; ++i)

x , x -1.

-->:

    int count = x();
    while( count --> 0 )

.;)

+7

Source: https://habr.com/ru/post/1538779/


All Articles