本征是否假设混叠?

Does Eigen assume aliasing?

本文关键字:假设 是否      更新时间:2023-10-16

矩阵乘法是特征中唯一默认采用混叠的操作。

MatrixXf mat1(2,2); 
mat1 << 1, 2,  4, 7;
MatrixXf mat2 = mat1;
auto result = mat1 * mat2;

Eigen 在临时矩阵中评估乘积mat1 * mat2,然后在计算后用于初始化result。由于result没有出现在右侧,因此我们不需要混叠:

MatrixXf result;
result.noalias() = mat1 * mat2;

现在,产品mat1 * mat2直接评估为result

目前为止,一切都好。但是在这种情况下会发生什么?

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;
}

我会说没有发生混叠,因为multiplication(m1,m2)是一个rvalue,并且由于 RVO 直接在result中构建。我会对行说同样的话mat1 = multiplication(mat1, mat2).然后我们可以说有一种方法可以将mat1与另一个矩阵相乘,并将结果存储在相同的矩阵mat1中,而无需使用临时矩阵(因此,避免混叠(。

问题

本征在这里假设混叠还是我的假设是正确的?

您还应该阅读有关使用auto关键字的常见陷阱。

如果你写

MatrixXf mat1, mat2;
auto result = mat1 * mat2;

template <typename T1, typename T2>
auto multiplication(const T1& A, const T2& B) { return A*B; }

那么auto的类型实际上只是类似于Product<MatrixXf, MatrixXf>Product<T1,T2>,即在这一点上根本没有计算发生。

因此

MatrixXf mat1 = MatrixXf::Random(2,2), mat2 = MatrixXf::Random(2,2);
auto result = multiplication(mat1, mat2); // no computation happens here
// this is safe (Eigen assumes aliasing can happen):
mat1 = result; // equivalent to directly assign mat1 = mat1 * mat2;
// Pitfall: "result" now refers to a modified `mat1` object!
// this will give undefined results (you may need bigger matrices to actually see this):
mat1.noalias() = mat1*mat2; // tell Eigen this does not alias, but actually it does.

附录:在评论中指出了赋值和初始化之间的区别。事实上,在初始化过程中,Eigen 假设没有发生混叠,例如,以下直接分配给结果(没有临时(:

MatrixXf result = mat1 * mat2; // initialization, not assignment!

附录 2:如果您编写(假设foo的返回类型为Object(:

Object A;
A = foo(A);

必须发生某种隐式赋值(如果Object允许的话,C++11 可能是移动赋值(。这与

Object A;
Object B = foo(A); // RVO possible (depending on foo).