Operator + for matrices in C++

c++, matrix, operators

Solution

The C++ standard gives permission for the compiler to elide the unnecessary copy in this case (it's called the "named return value optimization", usually abbreviated to NRVO). There's a matching "RVO" for when you return a temporary instead of a named variable.

Nearly all reasonably recent C++ compilers implement both NRVO and RVO, so generally speaking you can ignore the fact that this construct wouldn't otherwise be particularly efficient.

Edit: I was, of course, talking about the copy involved in returning the new matrix holding the result of the addition. You probably do want to either pass the input by const reference:

Matrix operator+(Matrix const &other) const { 
    Matrix result;
    // ...
    return result;
}

...or else, pass by value, but return the passed value:

Matrix operator+(Matrix other) const { 
    other += *this;
    return other;
}

Note that this depends on commutativity though (i.e., it's really doing `b+a` instead of `a+b`) so while it's fine for addition, it won't work for some other operations.

Problem

I suppose the naive implementation of a + operator for matrices (2D for instance) in C++ would be: ``` class Matrix { Matrix operator+ (const Matrix & other) const { Matrix result; // fill result with *this.data plus other.data return result; } } ``` so we could use it like ``` Matrix a; Matrix b; Matrix c; c = a + b; ``` Right? But if matrices are big this is not efficient as we are doing one not-necessary copy (return result). Therefore, If we wan't to be efficient we have to forget the clean call: ``` c = a + b; ``` Right? What would you suggest / prefer ? Thanks.

Original source