Perotto
Perotto

Reputation: 336

Error during program execution in function that returns another function

I try to call the 'testfun' function inside 'test' function using 'std::function', reducing variables number by 1 and performing intermediate calculations.

The 'A' class (vector) contains a 1D array of double.

During execution the program terminates at the specified point and 'functional' file is opened on 'const auto _Impl = _Getimpl();' line. How to solve the problem?

#include <functional>

class A
{
public:
    double* d;
    unsigned s;

    A(unsigned size)
    {
        s = size;
        d = new double[s];
    }
};

double testfun(A* param, A* x)
{
    return param->d[0] + param->d[1] * x->d[0];
}

std::function<double(A*)> anon(std::function<double(A*, A*)> f, A& x, A& y)
{
    std::function<double(A*)> result = [&](A * param_)
    {
        // Program fails somewhere at that point

        double sum = 0.0;

        for (unsigned i = 0; i < x.s; i++)
            sum += f(param_, &x) - y.d[i];

        return sum;
    };

    return result;
}

double test(std::function<double(A*, A*)> f)
{
    A x(1); A y(1);
    x.d[0] = 0.0;
    y.d[0] = 2.0;

    A* param = new A(2);
    param->d[0] = 2.0; param->d[1] = 6.0;

    std::function<double(A*)> func = anon(f, x, y);

    return func(param);
}

void main()
{
    double t = test(testfun);
}

Upvotes: 1

Views: 157

Answers (1)

max66
max66

Reputation: 66210

Not sure that is the only problem but is a problem.

In the following function

std::function<double(A*)> anon(std::function<double(A*, A*)> f, A& x, A& y)
{
    std::function<double(A*)> result = [&](A * param_)
    {
        // Program fails somewhere at that point

        double sum = 0.0;

        for (unsigned i = 0; i < x.s; i++)
            sum += f(param_, &x) - y.d[i];

        return sum;
    };

    return result;
}

the returned lambda receive f by reference bit anon() receive f by copy.

So when you call the returned lambda outside anon(), it contains a dangling reference to f.

Suggestion: try passing f, to the lambda, by copy.

// ....................................V  f by copy
std::function<double(A*)> result = [&, f](A * param_)
 { /* lambda content */ }

Upvotes: 2

Related Questions