Search code examples
c++classdestructoreigen

How can I call a destructor of a templated class?


I am using the SparseMatrix class of the library Eigen. To create one, I use:

typedef Eigen::SparseMatrix<float>  matrix;
matrix M (10,10);

How can I call the destructor of this object ?


Solution

  • (...) because I need to reinitialize the same sparse matrix several times in a loop. I hope that destructing the matrix every time by its destructor will lead to minimal memory leakage.

    The clear, obvious, safest, and probably most efficient solution is to just use the normal C++ semantics. "Reinitialization" is done with assignment.

    typedef Eigen::SparseMatrix<float>  matrix;
    matrix M (10,10);
    M = matrix(12, 12);
    

    Declare the matrix inside the loop body, and it will be properly initialized and destroyed at every loop iteration.

    Oh, and assuming a non-buggy library, there is zero memory leakage in all these cases. Just don't toss news around and don't play with fire (like calling destructors directly).