In the past few days, I have read "C ++ programming specifications: http://book.douban.com/subject/1459007/》to the 30th :“to avoid duplicate &&&,||or, (comma)", and I have never been completely confused. I understand it today. It turns out this is the case:
The built-in & (logical and), | (logical or) and (comma) operators always meet the following requirements:
Evaluate the operands from left to right;
For & operators, if the left operand is false, the right operand will not be evaluated, so we can safely write down
[Cpp]
If (p & p-> next)
This Code does not need to worry that when p is 0, p-> next will be evaluated first;
Similarly, for the | Operator, if the left operand is true, the right operand is not evaluated.
The above 2nd points and 3rd points are also called "Short Circut Evaluation )".
What happens if we reload these three operators? In fact, when an operator is overloaded, the compiler treats the operator as a function rather than a real operator. All parameters of a function are evaluated, and the order of values is undefined. Therefore, none of the above three properties can be satisfied!
Consider the following program:
[Cpp]
# Include <iostream>
# Include <string>
Using namespace std;
String retString ()
{
Cout <"string" <endl;
Return "hello ";
}
Int retInt ()
{
Cout <"int" <endl;
Return 47;
}
Int main ()
{
RetInt (), retString ();
}
No matter what compiler is used, as long as it supports the C ++ standard, the output of the program should be
Int
String
However, if the comma operator is overloaded, it is as follows:
[Cpp]
Void operator, (int a, const string & B)
{
}
After compiling with VS2010, the program will first output the string and then the int. It can be seen that the operands are evaluated from the right to the left.
If you make a few changes to the definition of the overload:
[Cpp]
Void operator, (const int & a, const string & B)
{
}
That is, the definition of the left operand a is changed to a constant reference. Then the program will output int and string again. You may suspect that the program calls the built-in comma operator at this time. You can add a cout output statement in the overload definition to know whether the called operator is actually a heavy-load operator. But the Parameter definition has been changed, and the order of parameter evaluation has changed. Is it amazing "?
From Zi zixiang's column