作为参数传递给函数的 Eigen MatrixXd 指针会导致分段错误

Eigen MatrixXd pointer passed as argument to a function causes segmentation faults

Eigen library has limitations with passing non-const Eigen variables as parameters to functions due so some issues with temporary object creation. However, they have provided several solutions and work arounds mentioned here 建议使用 Ref 模板化 class 或传递 const 参数,并在函数中放弃它们的常量。

但是,他们没有提到将特征矩阵作为函数指针传递的任何限制。

void function(const int a, Eigen::MatrixXd* mat) {
   Eigen::MatrixXd temp_mat = Eigen::Matrix::Constant(2, 2, a);
   (*mat).topLeftCorner << temp_mat; 
}

Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(5,5);
function(9, &mat);           // Seg Fault

我不确定为什么我会在此代码段中遇到分段错误。

void foo(const int a, Eigen::MatrixXd* mat)
{
    Eigen::MatrixXd temp_mat = Eigen::MatrixXd::Constant(2, 2, a);
    (*mat).topLeftCorner(2, 2) << temp_mat;
}


int main()
{
    Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(5, 5);
    foo(9, &mat); 
    cout << mat;
}

对我来说很好。