F
florian kno
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(const cMatrix& m1, const cMatrix& m2) const;
....
}
cMatrix cMatrix::row(const int& r) const {
cMatrix *tmp=new cMatrix(1,ncols);
for(int i=0;i<ncols;i++) (*tmp)=data[r*ncols + i];
return *tmp;
}
const double& cMatrix::dotproduct(const cMatrix& v1, const cMatrix& v2)
const {
double d=0.0;
for(int i=0;i<v1.elements();i++) d+=v1*v2;
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)="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!
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(const cMatrix& m1, const cMatrix& m2) const;
....
}
cMatrix cMatrix::row(const int& r) const {
cMatrix *tmp=new cMatrix(1,ncols);
for(int i=0;i<ncols;i++) (*tmp)=data[r*ncols + i];
return *tmp;
}
const double& cMatrix::dotproduct(const cMatrix& v1, const cMatrix& v2)
const {
double d=0.0;
for(int i=0;i<v1.elements();i++) d+=v1*v2;
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)="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!