I got different results using auto and using Vector
when summing two vectors.
My code:
#include "stdafx.h"
#include <iostream>
#include "D:\externals\eigen_3_1_2\include\Eigen\Geometry"
typedef Eigen::Matrix<double, 3, 1> Vector3;
void foo(const Vector3& Ha, volatile int j)
{
const auto resAuto = Ha + Vector3(0.,0.,j * 2.567);
const Vector3 resVector3 = Ha + Vector3(0.,0.,j * 2.567);
std::cout << "resAuto = " << resAuto <<std::endl;
std::cout << "resVector3 = " << resVector3 <<std::endl;
}
int main(int argc, _TCHAR* argv[])
{
Vector3 Ha(-24.9536,-29.3876,65.801);
Vector3 z(0.,0.,2.567);
int j = 7;
foo(Ha,j);
return 0;
}
The results:
resAuto = -24.9536, -29.3876,65.801
resVector3 = -24.9536,-29.3876,83.77
Press any key to continue . . .
I understand that Eigen does internal optimization that generate different results. But it looks like a bug in Eigen and C++11.
The
auto
keyword tells the compiler to "guess" the best object based on the right hand side of the=
. You can check the results by addingto
foo
(don't forget to include<typeinfo>
).In this case, after constructing the temporary
Vector3
, theoperator+
method is called, which creates aCwiseBinaryOp
object. This object is part of Eigens lazy evaluation (can increase performance). If you want to force eager evaluation (and therefore type determination), you could useinstead of your line in
foo
.A few side notes:
Vector3
is identical to theVector3d
class defined in Eigen#include <Eigen/Core>
instead of#include <Eigen/Geometry>
to include most of the Eigen headers, plus certain things get defined there that should be.