hjk41的日志

Avatar

More Effective C++ 7: Never overload && || or ,

The operators && || and , always evaluate their parameters from left to right.

if(p!=NULL && p.size()!=0){...}


Here, we don't have to worry if p is NULL. For when p==NULL, p.size() will never be evaluated. That' called short-circuit. The same thing happens to ||:

if(p==NULL || p.size()==0){...}

What's operator , ?


for(int i=0,int j=0; i<10; ++i,++j){  // comma operator
   ...
}


The comma operator always evaluates the parameters from left to right, and then return the result of the right expression.

However, if we overload the there opeartors above. We can't behave exactly the same way. C++ compilers will evaluate all the parameters passed to a function, so there will be no short-circuit. And the order in which compilers evaluate the parameters is not defined in C++ specifications, thus there is no gurantee that they will be evaluated from left to right.
So never overload the three operators mentioned above.

for(int i=0,int j=0; i<10; ++i,++j){ // comma operator
这条语句是无法通过编译的,应该是
for (int i = 0, j = 0; i < 10; ++i, ++j) {

评论已关闭