2013-11-03 84 views
1

我有一些數學計算在C++,我正在轉向Eigen。以前我手動滾動了我自己的double*陣列,也使用了GNU科學圖書館的gsl_matrixEigen和動態分配

我困惑的是FAQ of 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 

回答

4

這是有效的。但是請注意,即使將陣列大小調整爲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