Eigen  5.0.1
 
Loading...
Searching...
No Matches
Common pitfalls

Compilation error with template methods

See this page .

Aliasing

Don't miss this page on aliasing, especially if you got wrong results in statements where the destination appears on the right hand side of the expression.

Alignment Issues (runtime assertion)

Eigen does explicit vectorization, and while that is appreciated by many users, that also leads to some issues in special situations where data alignment is compromised. Indeed, prior to C++17, C++ does not have quite good enough support for explicit data alignment. In that case your program hits an assertion failure (that is, a "controlled crash") with a message that tells you to consult this page:

http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html

Have a look at it and see for yourself if that's something that you can cope with. It contains detailed information about how to deal with each known cause for that issue.

Now what if you don't care about vectorization and so don't want to be annoyed with these alignment issues? Then read how to get rid of them .

The auto keyword

In short: do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing. In particular, do not use the auto keyword as a replacement for a Matrix<> type. Here is an example:

MatrixXd A, B;
auto C = A*B;
for(...) { ... w = C * v; ...}
Matrix< double, Dynamic, Dynamic > MatrixXd
Dynamic×Dynamic matrix of type double.
Definition Matrix.h:489

In this example, the type of C is not a MatrixXd but an abstract expression representing a matrix product and storing references to A and B. Therefore, the product of A*B will be carried out multiple times, once per iteration of the for loop. Moreover, if the coefficients of A or B change during the iteration, then C will evaluate to different values as in the following example:

MatrixXd A = ..., B = ...;
auto C = A*B;
MatrixXd R1 = C;
A = ...;
MatrixXd R2 = C;

for which we end up with R1 ≠ R2.

Here is another example leading to a segfault:

auto C = ((A+B).eval()).transpose();
// do something with C

The problem is that eval() returns a temporary object (in this case a MatrixXd) which is then referenced by the Transpose<> expression. However, this temporary is deleted right after the first line, and then the C expression references a dead object. One possible fix consists in applying eval() on the whole expression:

auto C = (A+B).transpose().eval();

The same issue might occur when sub expressions are automatically evaluated by Eigen as in the following example:

VectorXd u, v;
auto C = u + (A*v).normalized();
// do something with C
Matrix< double, Dynamic, 1 > VectorXd
Dynamic×1 vector of type double.
Definition Matrix.h:489

Here the normalized() method has to evaluate the expensive product A*v to avoid evaluating it twice. Again, one possible fix is to call .eval() on the whole expression:

auto C = (u + (A*v).normalized()).eval();

In this case, C will be a regular VectorXd object. Note that DenseBase::eval() is smart enough to avoid copies when the underlying expression is already a plain Matrix<>.

Header Issues (failure to compile)

With all libraries, one must check the documentation for which header to include. The same is true with Eigen, but slightly worse: with Eigen, a method in a class may require an additional #include over what the class itself requires! For example, if you want to use the cross() method on a vector (it computes a cross-product) then you need to:

#include<Eigen/Geometry>

We try to always document this, but do tell us if we forgot an occurrence.

Ternary operator

In short: avoid the use of the ternary operator (COND ? THEN : ELSE) with Eigen's expressions for the THEN and ELSE statements. To see why, let's consider the following example:

A << 1, 2, 3;
Vector3f B = ((1 < 0) ? (A.reverse()) : A);
Matrix< float, 3, 1 > Vector3f
3×1 vector of type float.
Definition Matrix.h:488

This example will return B = 1, 2, 3. Do you see why? The reason is that in c++ both statements of the ternary operator must be converted to a common type. The constructor of Reverse<Vector3f> from a Vector3f is explicit, so the ELSE statement A cannot be converted to a Reverse<Vector3f>; the common type is Vector3f instead, and the compiler thus generates:

Vector3f B = ((1 < 0) ? Vector3f(A.reverse()) : Vector3f(A));

The value is the expected one here, but the selected statement is silently evaluated into a temporary plain object, and two different Eigen expression types often have no common type at all, in which case the ternary operator does not even compile. The safest and fastest is really to avoid this ternary operator with Eigen's expressions and use a if/else construct.

Pass-by-value

If you don't know why passing-by-value is wrong with Eigen, read this page first.

Note
If you are compiling in C++17 mode with a sufficiently recent compiler (GCC >= 7, Clang >= 5, MSVC >= 19.12), the alignment issues described below are handled automatically by the compiler via over-aligned operator new, and pass-by-value is safe.

For pre-C++17 code, you have to watch out for templates which define argument types at compile time. If a template has a function that takes arguments pass-by-value, and the relevant template parameter ends up being an Eigen type, then you will have the same alignment problems that you would in an explicitly defined function passing Eigen types by value.

Using Eigen types with other third party libraries or even the STL can present the same problem. std::bind for example uses pass-by-value to store arguments in the returned functor.

There are at least two ways around this:

  • If the value you are passing is guaranteed to be around for the life of the functor, you can use std::ref() to wrap the value as you pass it to std::bind. Generally this is not a solution for values on the stack as if the functor ever gets passed to a lower or independent scope, the object may be gone by the time it's attempted to be used.
  • The other option is to make your functions take a reference counted pointer like std::shared_ptr as the argument. This avoids needing to worry about managing the lifetime of the object being passed.

Matrices with boolean coefficients

For bool coefficients, Eigen interprets the arithmetic operators in the Boolean semiring: + is the logical OR and * is the logical AND. In particular, the product of two bool matrices is a Boolean matrix product: coefficient (i,j) of A * B tells whether row i of A and column j of B share a true entry. This holds for every matrix size and every product implementation.

The Boolean semiring has no additive inverse, so subtraction (including -=) and unary minus are not supported for bool matrices or arrays. These operations produce a compile-time diagnostic. For integer arithmetic on 0/1 data, cast the operands to a signed integer type before the operation:

Matrix<bool, Dynamic, Dynamic> A(n, n), B(n, n);
A.setOnes();
B.setOnes();
MatrixXi C = A.cast<int>() * B.cast<int>() - A.cast<int>() * B.cast<int>(); // zero
Matrix< int, Dynamic, Dynamic > MatrixXi
Dynamic×Dynamic matrix of type int.
Definition Matrix.h:487

For coefficient-wise Boolean negation use !A.array(); for coefficient-wise XOR use A.array() != B.array().