Re: rvalue references and parameter passing
I ran some tests which some might find interesting. It turns out the
best version of a matrix multiply like this is below. I found this
interesting because of all of the articles out there talking about the
merits of passing by value. In most cases pass by value and rvalue
reference overloads are useful when you have move constructors, but in
this case there is no concept of a move constructor.
Anyway the best version is this:
Matrix4 operator+(const Matrix4& l, const Matrix4 & l) {
Matrix4 m(l);
m+= r;
return m;
}
I tested 4 cases by replacing the copy constructor with a print
statement and running the following:
Matrix4 m, n, x;
x = m + n;
x = m + Matrix4();
x = Matrix4() + n;
x = Matrix4() + Matrix4();
In all 4 cases, the const reference version does 1 copy. The reason is
because of Return value optimization. In all cases the only copy is
when we do m(l); The compiler is smart enough to construct the return
value directly into x.
If you do this version:
Matrix4 operator+(Matrix4 l, const Matrix4& r) {
l+= r;
return l;
}
Sometimes you get 2 copies. This happens in cases 1 and 2 because
return value optimization does not work when you return one of the
function parameters. So first the lvalue is copied into l, then the
return value is copied again into x.
One final note, don't do this:
Matrix4 operator+(const Matrix4& l, const Matrix& r) {
Matrix4 m(l);
return m+= r;
}
You might think you are being clever, but what you're returning now is
the return value of operator+= which is a Matrix4 reference. The
compiler has no way of knowing what this reference points to so it
cannot do RVO.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]