Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen and Dynamic Allocation

Tags:

c++

eigen

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
like image 874
Cardin Avatar asked Oct 20 '25 01:10

Cardin


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!