Article 20 assisting the compiler in implementing return value optimization
When overloading an operator, such as A +-*/Such operator, the value returned by the function must be an rvalue (that is, it cannot be a reference), and the overhead of performing an operation might be to invoke multiple constructors and destructors on the temporary object, which is a significant overhead. Now the new compiler has been able to optimize the situation, and even the optimization to even the cost of not, but there is a certain scope of application. If you can return an anonymous temporary object and use the constructor to get the result object, then it is possible to optimize to zero overhead. Note that a named object means that the return value optimization is not available.
Assume the following code:
1 Node A (2); 2 Node B (3); 3 Node c=a+b;
The prototype of the function is probably this:
1 Const Node Add (const node& A,const node& B)2{3 return node (a, b); 4 }
An anonymous temporary object is returned, but the compiler may be optimized or even 0 overhead (but the constructor cost of C is still needed). Even if there is no optimization, we try to do so with no harm.
Clause 22 Consider using op= to replace individual OP operators
In general, operator + only need to define operator + = can be implemented, the main purpose is to use the optimization in clause 20, that is, the use of constructors to achieve the function of the return value optimization. For example:
1 structnode2 {3 Public:4 Constnode&operator+= (Constnode& RHS)Const5 {6 ...7 return This;8 }9 };Ten One ConstNodeoperator+(Constnode& A,Constnode&b) A { - returnNode (a) + =b; -}
For the return value optimization, it might be better if inline is added.
These two articles are not very clear, just know that if such a child is more efficient, but certainly not cost more. There is no certainty in the book to say that this must be optimized.
"More effective C + +" clause 20 section 21