When you must return an object, don't be paranoid about returning it reference
We analyzed the benefits of object reference passing in the previous section, which now shows the disadvantages of returning a reference object from a function.
First, a piece of code:
Class rational{ Public:Rational(intNumerator=0,intDenominator=1); ......Private:intN, D; FriendConstRationaloperator*(Constrational& LHS,Constrational& rhs);};Constrational&operator*(Constrational& LHS,Constrational& RHS) {Rational result (lhs.n* RHS.N, lhs.d* rhs.d);returnResult;} Rational A (1,2), B (3,4); Rational &r=a*b;
Let's see if there is any problem with the above code, it is clear that R is a reference to the return value. It is obvious that the object ontology has been destroyed outside the scope of the operator* function, at which point the R object has been reclaimed by the system and the program is prone to errors.
So, what if the object is created dynamically in the function body?
The following code:
constoperator*(constconst Rational& rhs){ Rational* result=new Rational(lhs.n* rhs.n, lhs.d* rhs.d); return *result;}Rational w,x,y,z;w=x*y*z;
What's wrong with the above code?
Obviously caused a memory leak, two calls to the operator* function to create two dynamic memory objects, but finally there is no delete.
What if I create a static object?
constoperator*(constconst Rational& rhs){ static Rational result; result=……; return result;}booloperator==(constconst Rational& rhs);Rational a, b, c, d;……if((a*b)==(c*d)){ doSomething();}else{ doOtherthing();}
What's wrong with the above code?
The answer is that the values in the above code are (a*b)==(c*d)
always true. This is the characteristic of static! Therefore, the operator* function design is unreasonable, resulting in operator== error.
Speaking of summarizing now.
It is very simple to think that the function must return to the object when it is said, do not want to return its reference. What's the return? It is clear that the value of the object is returned instead of the reference.
Effective C + + terms