Incompatibility between the safe bool idiom and the explicit bool operator

I am thinking of replacing all instances of the safe idlom bool with an explicit operator bool in code that already uses the features of C ++ 11 (so the fact that older compilers do not recognize explicit conversion operators does not matter), so I would like to know can this cause some subtle problems.

So what are all the possible incompatibilities (even the smallest ones) that could be caused by the transition from the old and dumb safe idiom bool to the new and shiny explicit operator bool ?

EDIT: I know switching is a good idea, as the latter is a language function well understood by the compiler, so it will work no worse than actually hacking. I just want to know the possible differences.

+7
c ++ language-lawyer c ++ 11 safe-bool-idiom
source share
2 answers

Probably the biggest difference, assuming your code is error-free (I know, not a safe assumption), will be that in some cases you may need an implicit conversion to exactly bool . The explicit conversion function will not match.

 struct S1 { operator S1*() { return 0; } /* I know, not the best possible type */ } s1; struct S2 { explicit operator bool() { return false; } } s2; void f() { bool b1 = s1; /* okay */ bool b2 = s2; /* not okay */ } 
+4
source share

If you used conversion from safe-bool to your code incorrectly, only then the explicit operator bool should be incompatible, as this will not allow you to do something wrong so easily. Otherwise, it should be perfect, without any problems. In fact, even if there is a problem, you should still switch to explicit operator bool , because if you do, then you can identify the problem when using the safe-bool transform.

According to this article, some compilers give inefficient instructions for implementing safe-bool using a member function pointer,

When people started using this idiom, it was discovered that on some compilers the level of efficiency was reduced - a pointer to a member function called the head of the compiler, which led to a slower execution when the address was selected. Although the difference is marginal, current practice is usually to use an element data pointer instead of a member function pointer.

+3
source share

All Articles