Hi!
"Karl Heinz Buchegger" <kbuchegg@gascad.at> wrote in message
news:3F8FA4F8.2E45DB52@gascad.at...[color=blue]
> Risto Lankinen wrote:[color=green]
> > Why do you think implementing op+ using op+= is more
> > efficient than vice versa?[/color]
>
> Because for operator+ you need a temporary object.
> For operator+= you don't need this temporary.
>
> So if you implement += in terms of +, you implicitely
> add the creation of a temporary to +=. And that comes
> with some costs.[/color]
Ah, now I see. For "simple" objects this may well be
a good heuristic, but for more complex (not Complex :-)
objects you will run into problems with exception safety.
Implementing op+= using op+ will necessarily call op=
in its implementation, providing a good single place for
exception safe assignment with roll-back capability.
[color=blue][color=green]
> > Consider that in a typical program op+
> > is far more often used than op+= .[/color]
>
> That's not an issue most of the time. Functions like that
> are inlined by any decent compiler.[/color]
But inlining works in both cases. The op+ needs to
create a temporary object (namely the result) in any
case, but in the case of using op+= the temporary
object has a named storage. If it is possible to use
new object construction with arguments to create
the result of the addition, as in...
inline Complex operator+( const Complex &lhs,const Complex &rhs )
{
return Complex( lhs.Real()+rhs.Real(),lhs.Imag()+rhs.Imag() );
}
.... then you will generally bypass the extra construction
with most compilers because the unnamed return value
optimization has room to kick in, effectively collapsing
the extra construction with the one that it has to do in
any case.
[color=blue][color=green]
> > I would also consider making the op+= a non-member
> > function, too.[/color]
>
> Why?[/color]
If it can be implemented as a non-member function using
only the public interface of the class itself, it should. There
has been an article by Scott Meyer in CUJ titled "How
non-members improve encapsulation". (I tried to locate a
link, but the CUJ web site seems to be down. I believe
this link will load the article but I could not verify myself:)
http://www.cuj.com/archive/1802/feature.html
Cheers!
- Risto -