Yang Wang
Yang Wang

Reputation: 335

C++ Operator+ Overloading of Matrix

I am learning to build my own Matrix class and get a question on the operator+ overloading.

Matrix Matrix::operator+(Matrix &b)
{
    Matrix temp;
    *
    *
    *
    return temp;
}
c = a + b;

This works very well but I am a little concerned that is it inefficient that I declare a temporary matrix first then copy it to the final target (matrix c)? For example, below is a naive matrix add function,

void matrixAdd(Matrix& c, Matrix& a, Matrix& b)
{
    c[][]=a[][]+b[][];
}

Off course, the first one is easier to use but will the second be faster? If so, how can I improve the first one?

Upvotes: 3

Views: 195

Answers (1)

Bathsheba
Bathsheba

Reputation: 234705

Your snippet is fine with modern compilers.

They will optimise out an apparent deep copy of temp using a technique called named return value optimisation.

In other words the compiler will make the improvements in the first snippet for you, and the second one will wind up being no faster. For more details, see https://en.wikipedia.org/wiki/Return_value_optimization

Finally though, it's a good idea to change the prototype to

Matrix Matrix::operator+(const Matrix &b) const

so you are able to apply the operator to const arguments.

Upvotes: 6

Related Questions