Reputation: 5507
I have some mathematically computations in C++ that I'm moving to Eigen. Previously I've manually rolled my own double*
arrays and also used gsl_matrix
from the GNU Scientific Library.
What confused me was the wording in the FAQ of Eigen. What does that mean, is it that there's some kind of reference counting and automatic memory allocation going on?
And I just need to confirm that this is still valid in 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
Upvotes: 4
Views: 11945
Reputation:
This is valid. However, note that even if you resize the array to 0
, the MatrixXd
object will still exist, just not the array it contains.
{
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
Avoid new
and use automatic storage duration whenever possible. In other cases, use std::unique_ptr
.
Upvotes: 8