This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Eigen Vectors and lambda functions

Tags: None
(comma "," separated)
filippol
Registered Member
Posts
1
Karma
0

Eigen Vectors and lambda functions

Thu Dec 17, 2015 8:29 am
I am having troubles finding out why a piece of code doesn't work as I'm expecting.

Consider the following M(N)WE:
Code: Select all
#include <Eigen/Dense>
#include <iostream>

int main(void) {
   
    const Eigen::Vector3d a = { 1., 2., 3. };
    const Eigen::Vector3d b = { 3., 5., 6. };
    auto f = [&a] (const Eigen::Vector3d & y) -> Eigen::Vector3d {
        return a.cross(y) + y;
    };
    auto g = [&a] (const Eigen::Vector3d & y) {
        return a.cross(y) + y;
    };
   
   Eigen::Vector3d v;
   v = f(b);
   std::cout << v << std::endl;
   v = f(b) - f(b);
   std::cout << v << std::endl;
   
   Eigen::Vector3d w;
   w = g(b);
   std::cout << w << std::endl;
   w = g(b) - g(b);
   std::cout << w << std::endl;
}


The output should be the same for both functions (f(b) = g(b)). However I get two different results.

Automatic return type deduction should deduce the return type of $f$ to be some vector expression. However, when assigning to v, the copy constructor should be called correctly. There is no aliasing issue here.

I cannot figure out where/why the program breaks. Any ideas?

PS: compiled with gcc c++11
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
The function g is invalid because cross returns a temporary which is then referenced by the addition expression returned by g, but this reference becomes invalid after the function returned.


Bookmarks



Who is online

Registered users: bartoloni, Bing [Bot], Evergrowing, Google [Bot]