特征和动态分配

时间:2013-11-03 10:00:33

标签: c++ eigen

我在C ++中有一些数学计算,我正在转向Eigen。以前我手动滚动了我自己的double*数组,并使用了GNU Scientific Library中的gsl_matrix

令我感到困惑的是FAQ of Eigen中的措辞。这意味着什么,是否存在某种引用计数和自动内存分配?

我只需要确认这在Eigen中仍然有效:

// n and m are not known at compile-time
MatrixXd myMatrix(n, m);
MatrixXd *myMatrix2 = new MatrixXd(n, m);

myMatrix.resize(0,0); // destroyed by destructor once out-of-scope
myMatrix2->resize(0,0);
delete myMatrix2;
myMatrix2 = NULL; // deallocated properly

1 个答案:

答案 0 :(得分:5)

这是有效的。但请注意,即使您将数组调整为0MatrixXd对象仍然存在,而不是它包含的数组。

{
    MatrixXd myMatrix(n, m); // fine
} // out of scope: array and matrix object released.

{
    auto myMatrix = new MatrixXd(n, m); // meh
    delete myMatrix; // both array and matrix object released
}

{
    auto myMatrix = new MatrixXd(n, m); // meh
    myMatrix->resize(0, 0); // array released
} // out of scope: matrix object leaks

尽可能避免使用new并使用自动存储时间。在其他情况下,请使用std::unique_ptr

相关问题