我在 Eigen 文档中关注此页面,试图了解 Eigen 参数的使用
https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
以下代码按预期工作
#include <iostream>
#include <Eigen/Dense>
// a - nonwriteable, b - writeable
void eigen_reference_class(
const Eigen::Ref<const Eigen::Array<double,
Eigen::Dynamic, 3> >& a, Eigen::Ref<Eigen::Array<double, Eigen::Dynamic, 3> > b) {
b = 2 * a;
}
void eigen_reference(const Eigen::Array<double, 1, 3>& a, Eigen::Array<double, 1, 3>& b) {
b = 2*a;
}
template<typename Derived>
void eigen_template(const Eigen::PlainObjectBase<Derived>& a, Eigen::PlainObjectBase<Derived>& b) {
b = 2*a;
}
int main()
{
Eigen::Array<double, 1, 3> a, b, c, d;
a << 1, 2, 3;
eigen_reference_class(a, b);
eigen_reference(a, c);
eigen_template(a, d);
std::cout << "a : \n" << a << std::endl;
std::cout << "b: \n" << b << std::endl;
std::cout << "c: \n" << c << std::endl;
std::cout << "d: \n" << d << std::endl;
}
但是,如果数组的初始声明更改为
Eigen::Array<double, Eigen::Dynamic, 3> a, b, c, d;
然后程序将无法通过以下方式编译:
error: invalid initialization of non-const reference of type ‘Eigen::Array<double, 1, 3>&’ from an rvalue of type ‘Eigen::Array<double, 1, 3>’
eigen_reference(a, c);
或者即使只a
保留定义,也会因分段错误而失败。