Some brief notes for quick reference.
It occurs when the same matrix or array coefficients appear both sides of an assignment operator. In general
noalias();
noalias(), you also get wrong results;
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.
Common concepts,
MatrixBase, base class for all dense matrix expressions;
ArrayBase, base class for all dense array expressions;
DenseBase, base class for MatrixBase and ArrayBase;
EigenBase, base class for DenseBase and other Eigen objects;
Eigen::EigenBase<Derived>::derived(), returns a const reference to the derived object;
Options for generic non-template functions,
const Eigne::Ref<const T>& for a const reference;
Eigen::Ref<T> for a writable reference;