Odd behaviour when capturing an Eigen::Vector in std::function

Viewed 51

I have the following code

Eigen::Vector2d xT = Eigen::Vector2d(1.7, 3.4); // chosen at random

std::function<Eigen::Vector2d(Eigen::Vector2d)> test1 = [xT](Eigen::Vector2d x)
{ 
    Eigen::Vector2d y = x - xT;
    return y; 
};

std::function<Eigen::Vector2d(Eigen::Vector2d)> test2 = [xT](Eigen::Vector2d x)
{ 
    return x - xT; 
};

std::cout << "\n" << test1(xT) << "\n"; // outputs (0, 0) i.e. x - xT
std::cout << "\n" << test2(xT) << "\n"; // outputs (-1.7, -3.4) i.e. -xT

I would think that both test1 and test2 should output the same results. Yet test2 is outputting erroneous results (it is evaluating at (0,0) rather than at xT). What is happening here?

I tried similar things with doubles rather than Eigen::Vector2d but everything worked fine.

0 Answers
Related