hello all!
i'm using gcc 3.2 on linux.
i have a (self developed) matrix class:
class cMatrix { // unneccessary info stripped
....
double *data; // matrix data is stored in a heap array
cMatrix row(const int& r) const;
// const cMatrix& row(const int& r) const; // is this better?? why?
....
const double& dotproduct(cons t cMatrix& m1, const cMatrix& m2) const;
....
}
cMatrix cMatrix::row(co nst int& r) const {
cMatrix *tmp=new cMatrix(1,ncols );
for(int i=0;i<ncols;i++ ) (*tmp)[i]=data[r*ncols + i];
return *tmp;
}
const double& cMatrix::dotpro duct(const cMatrix& v1, const cMatrix& v2)
const {
double d=0.0;
for(int i=0;i<v1.elemen ts();i++) d+=v1[i]*v2[i];
return d;
}
int main() {
{
cMatrix m(10,10);
cMatrix r=m.row(1);
}
return 0;
}
using valgrind i found out that the above main() leaks memory.
my questions are:
* how to alter the code of cMatrix::row to avoid memory leaks?
* how to avoid objects stored on the stack that get overriden later
when program code is further executed?
* is there a better syntax for (*tmp)[i]="some value"?
additional info:
* i later definitly need something like
res=dotproduct( Ni, nodes.column(i) ); (where Ni is also a matrix)
to work correctly.(^^^^ ^^^^^^^^^^^ temporary object)
-> operator and method chaining.
thanks for any help or ideas!
--
flo
i'm using gcc 3.2 on linux.
i have a (self developed) matrix class:
class cMatrix { // unneccessary info stripped
....
double *data; // matrix data is stored in a heap array
cMatrix row(const int& r) const;
// const cMatrix& row(const int& r) const; // is this better?? why?
....
const double& dotproduct(cons t cMatrix& m1, const cMatrix& m2) const;
....
}
cMatrix cMatrix::row(co nst int& r) const {
cMatrix *tmp=new cMatrix(1,ncols );
for(int i=0;i<ncols;i++ ) (*tmp)[i]=data[r*ncols + i];
return *tmp;
}
const double& cMatrix::dotpro duct(const cMatrix& v1, const cMatrix& v2)
const {
double d=0.0;
for(int i=0;i<v1.elemen ts();i++) d+=v1[i]*v2[i];
return d;
}
int main() {
{
cMatrix m(10,10);
cMatrix r=m.row(1);
}
return 0;
}
using valgrind i found out that the above main() leaks memory.
my questions are:
* how to alter the code of cMatrix::row to avoid memory leaks?
* how to avoid objects stored on the stack that get overriden later
when program code is further executed?
* is there a better syntax for (*tmp)[i]="some value"?
additional info:
* i later definitly need something like
res=dotproduct( Ni, nodes.column(i) ); (where Ni is also a matrix)
to work correctly.(^^^^ ^^^^^^^^^^^ temporary object)
-> operator and method chaining.
thanks for any help or ideas!
--
flo
Comment