-
Destructor question
Hi,
I ran into a destructor problem that is illustrated in the following code. I have used a stripped down matrix class. The problem is the destructor is invoked when the function testfunc ends. I think the destructor deallocates the memory pointed to by secondmatrix.p. That also means the memory pointed to by firstmatrix.p is deallocated. How do I avoid this so I can continue using firstmatrix later in main.
Thanks,
Peter
Code:
// - - - - - - - - - main.cpp - - - - - - - - - - - -
#include <stdlib.h>
#include "matrix.h"
using namespace std;
void testfunc(matrix secondmatrix){
//doesn't matter what happens in here
}
int main(void) {
matrix firstmatrix(4,5);
testfunc(firstmatrix);
//at this point isn't the memory pointed to by firstmatrix.p gone?
system("PAUSE");
return 0;
}
// - - - - - - - - - matrix.h - - - - - - - - - - - -
#ifndef MAT_H
#define MAT_H
using namespace std;
class matrix {
public:
matrix(){;}
matrix(long,long);
~matrix(){delete [] p;}
protected:
double *p;
long r; /*number of rows*/
long c; /*number of columns*/
};
#endif
// - - - - - - - - - - matrix.cpp - - - - - - - - - - -
#include <assert.h>
#include "matrix.h"
using namespace std;
matrix::matrix(long rows, long cols){
r = rows;
c = cols;
p = new double [rows*cols];
assert (p != 0);
}
-
Maybe include a copy constructor?
-
You need to pass it by reference. You are currently passing it by value, clearly not what you want. When you pass it by value the original variable in main will not get changed. A temporary copy is created and used in the function and gets destroyed at the end of the function's scope ( hence the destructor call ). What you want is something like...
Code:
void testfunc(matrix &secondmatrix){
//doesn't matter what happens in here
}
You could also pass it as a pointer but you can mess with that on your own. Passing it by reference won't change how you call the function, just how it is passed into it.
-
I would go with a copy constructor and a reference counter or a passage by reference like MrWizard said, however, I prefer the pointers if you're function's intended to use non-constant access to the matrix... But it is a matter of opinion.