我在C ++中进行了一些数学计算,现在我正要转到Eigen。以前,我是手动滚动自己的double*
数组,也可以gsl_matrix
在GNU科学库中使用。
使我困惑的是Eigen的FAQ中的措辞。这是什么意思,就是正在进行某种引用计数和自动内存分配?
我只需要确认这在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
这是有效的。但是,请注意,即使将数组的大小调整为0
,该MatrixXd
对象仍将存在,只是它所包含的数组不存在。
{
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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句