Matrix multiplication is the only operation in Eigen that assumes aliasing by default.
MatrixXf mat1(2,2);
mat1 << 1, 2, 4, 7;
MatrixXf mat2 = mat1;
auto result = mat1 * mat2;
Eigen evaluates the product mat1 * mat2
in a temporary matrix which is then used to initialize result
after the computation. As result
does not appear in the right hand side, we do not need aliasing:
MatrixXf result;
result.noalias() = mat1 * mat2;
Now, the product mat1 * mat2
is directly evaluated into result
.
So far, so good. But what happens in this case?
template <typename T1, typename T2>
auto multiplication(const T1& A, const T2& B) // I'm using C++17, decltype not needed
{
return A*B;
}
int main()
{
auto result = multiplication(mat1, mat2); // say mat1 and mat2 are the same as above
// or even this
mat1 = multiplication(mat1, mat2);
return 0;
}
I would say no aliasing occurs as the multiplication(m1,m2)
is an rvalue
and constructed directly in result
thanks to RVO. And I would say the same for the line mat1 = multiplication(mat1, mat2).
We could then say that there is a way to multiply mat1
with another matrix and store the result in the same matrix mat1
without using a temporary matrix (so, avoiding aliasing).
Question:
Does Eigen assume aliasing here or is my assumption correct?
auto result = mat1 * mat2;
as an assignment. – Joiejoinauto result = mat1 * mat2;
is (in C++17) an initialization, not an assignment. It does not useoperator=
. – Pridgen