Eigen 101 · Aliasing, Function Arguments and Reference

Apr 5, 2025 | Tech Software

Some brief notes for quick reference.

Aliasing

It occurs when the same matrix or array coefficients appear both sides of an assignment operator. In general

  • when you multiply two matrices, Eigen assumes that aliasing occurs; if you know that there is no aliasing, then you can use noalias();
  • when Eigen assumes aliasing but you apply noalias(), you also get wrong results;
  • In all other situations, Eigen assumes that there is no aliasing issue and thus gives the wrong result if aliasing does in fact occur; to prevent this, you have to use eval() or one of the xyzInPlace() functions.
mat = 2 * mat;                // exhibits aliasing, but harmless
mat = mat.transpose();        // exhibits aliasing, leads to unexpected results
mat = mat.transpose().eval(); // no aliasing, less efficient
mat.transposeInPlace();       // no aliasing, preferred
mat = mat * mat;              // exhibits aliasing but Eigen assumes and handles that, so the result is correct
mat = (mat * mat).eval();     // explicitly requesting `eval()`, less efficient but result is correct
mat.noalias() = mat * mat     // explicitly specifying `noalias()` while Eigen assumes aliasing, leads to wrong result

The following summarizes aliasing and solutions by example. For details, see Aliasing and Common pitfalls from Eigen Documentation.

Function Arguments and Reference

Common concepts,

Options for generic non-template functions,