While developing a Matrix class, I ran into a problem and I'd like your points of view.
I have an Add method, which is
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::tr1::shared_ptr<Matrix> Add(const Matrix& other) const{
if(this->nRows != other.nRows || this->nCols != other.nCols){
throw"Number of elements must be equal in both matrixes";
}
Matrix * pResult = new Matrix(nRows, nCols);
std::tr1::shared_ptr<Matrix> ptr(pResult);
for(unsignedint i = 0; i < nRows; i++){
for(unsignedint j = 0; j < nCols; j++){
T aux = GetElement(i, j) + other.GetElement(i, j);
pResult->SetElement(i, j, aux);
}
}
return ptr;
}
I'm returning a smart pointer to the method caller, forcing it to handle a shared_ptr object. Is this the best way of doing it? Should I return a Matrix object and comment that Matrix is dynamically allocated instead?
I do not use a Matrix parameter by reference because I want to overload the "+" operator.
IMO, this whole scheme is wrong. Idiomatically, the prototype of an operator+() overload should be T T::operator+(const T &) const. Either use smart pointers throughout or not at all. The correct scheme would then be
1 2 3 4 5 6 7 8 9
class MatrixInternal;
class Matrix{
//Opaque pointer (pimpl + smart pointer):
shared_ptr<MatrixInternal> p;
//No other data members.
public:
//Your overloads here.
};