|
Boost : |
From: Daniel Frey (daniel.frey_at_[hidden])
Date: 2004-01-12 04:46:40
Howard Hinnant wrote:
> On Jan 9, 2004, at 9:27 PM, David Abrahams wrote:
>
>> "Peter Dimov" <pdimov_at_[hidden]> writes:
>>
>>> Executive summary: the reference wins. It doesn't really matter. You
>>> knew
>>> that already.
>>
>> Yep, my tests show the same. That's a relief to me, actually. I
>> wonder what Andrei was on about?
>
> Andrei was making a point that Peter's test does not elucidate.
>
> If you must modify the argument internally, then it is better to pass
> the argument by value and modify the argument directly, rather than pass
> by const reference, and make a copy of the argument which you can then
> modify:
Consider:
struct X {
X() { cout << "X()\n"; }
X( const X& ) { cout << "X(X)\n"; }
X& operator+=( const X& ) { cout << "+=\n"; }
};
X operator+( const X& lhs, const X& rhs ) {
X nrv( lhs );
nrv += rhs;
return nrv;
}
X operator-( X lhs, const X& rhs ) {
lhs += rhs;
return lhs;
}
int main() {
{
X a,b,c;
cout << "--\n";
a + b + c;
cout << "--\n";
a - b - c;
cout << "--\n";
a + ( b + c );
cout << "--\n";
a - ( b - c );
cout << "--\n";
}
}
Try this on a compiler that implements the NRVO. (GCC3.1+, Intel7+
(->EDG), MSVC8+). Conclusion: Even when you need a copy of the argument,
the const reference can save you some copies. See also
<http://tinyurl.com/yvabj>. IIRC, Andrei's point was that not all
compilers implement the NRVO, but the situation is getting better and
better... :)
Regards, Daniel
-- Daniel Frey aixigo AG - financial solutions & technology Schloß-Rahe-Straße 15, 52072 Aachen, Germany fon: +49 (0)241 936737-42, fax: +49 (0)241 936737-99 eMail: daniel.frey_at_[hidden], web: http://www.aixigo.de
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk