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 ?
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 ?
You don't need to. Your object is being created on the stack and will be automatically deleted when it goes out of scope.
(...) 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 new
s around and don't play with fire (like calling destructors directly).
You don't call the destructor directly; it will be invoked when this variable goes out of scope.
void myFunction()
{
matrix A (10,10);
... some code
{
matrix B (10,10);
} // destructor of B is called here.
... some code
}// destructor of A is called here.
This is the behavior of an auto variable as you have in your code. The other way to invoke a destructor is if you have dynamically allocated the object with new
, and you destroy the object with delete
:
void myFunction()
{
matrix* A = new matrix(10,10);
... some code
{
matrix* B = new matrix(10,10);
delete B;// destructor of B is called
}
... some code
delete A;// destructor of A is called
}
There is only one case that I know of where you need to call a destructor explicitly: When using placement new, e.g.
class Foo { /* lots of stuff here */ };
char foo[sizeof(Foo)];
new (&foo[0]) Foo();
/* ... */
reinterpret_cast<Foo *>(&foo[0])->~Foo();
While I'm really not sure why you want to do this, it is quite easy:
M.~SparseMatrix();
In general, you can explicitly invoke the destructor on any class, just by calling it like any other function. Templated classes are no different.