Hello, I'm wondering about the best way to return objects in class functions. The code I'm posting is an overloaded + operator that adds two matrices (created with valarrays), stores the result in a new matrix and returns a pointer to the matrix containing the result.
1 2 3 4 5 6 7 8 9 10 11 12 13
template <class T>
Matrix<T>& Matrix<T>::operator+ (Matrix<T>& rhs){
if((nRows_ != rhs.nRows_) || (nCols_ != rhs.nCols_))
throw BadSize("error; both matrices must be the same size");
Matrix<T>* result = new Matrix<T>(nRows_, nCols_);
for(unsigned i = 0; i < nRows_; ++i)
result->matrix_[i] = matrix_[i] + rhs.matrix_[i];
return *result;
}
It seems to me that this creates a memory leak (is that correct?). What is the best way to do this sort of thing?
The above function would be used in an expression of the form
a + b
where a and b are Matrix<T> objects.
That said, operator+ should not modify the value of either a or b.
Having said that, operator+ should be declared a const member function
and should take rhs by const reference.
Furthermore, operator+ should return a Matrix<T> by value, not by reference.
Having said that, it makes your problem much easier... don't dynamically
allocate a new matrix on the heap; create it on the stack. This fixes the
memory leak.