menu

hjk41的日志

Avatar

More Effective C++ 21: Overload to avoid implicit type conversions


class UPInt {                                 // class for unlimited
public:                                       // precision integers
  UPInt();
  UPInt(int value);
  ...

};
const UPInt operator+(const UPInt& lhs, const UPInt& rhs);

UPInt upi1, upi2, upi3;
upi3 = upi1 + 10;


Here, when we do upi3=upi1+10, we actually convert the integer 10 into a UPInt object first. However, this bring the construction of temporary objects, which we want to eliminate.
The way to achieve this is to declare the operator + taking arguments of type int explicitly.


const UPInt operator+(const UPInt& lhs,      // add UPInt
                      const UPInt& rhs);     // and UPInt

const UPInt operator+(const UPInt& lhs,      // add UPInt
                      int rhs);              // and int

const UPInt operator+(int lhs,               // add int and
                      const UPInt& rhs);     // UPInt


Now we can do upi3=upi1+10 without creating temporary objects.

评论已关闭