Overloading to avoid temporaries.
Consider following code:
|
|
And following statements:
|
|
These statements succeed by the creation of temporary objects to convert the integer 10 into UPInts
(MECpp item 19).
It is convenient to have compilers perform such kinds of conversions, but the we do pay the cost of implicit type conversion. If we want to eliminate this cost, we cancel the type conversions by function overloading;
|
|
Notice that const UPInt operator+(int, int);
is not allowed: C++ rules that every overloaded operator must take at leas one argument of a user-defined type. int
isn’t a user-defined type, so we can’t overload this operator+
in this form.
Still, before doing such optimizations, it’s important to follow the 80-20 rule (MECpp item 16) to make sure it will make a noticeable improvement in the overall efficiency of the programs.