To clarify what I wrote in some comments, here is the reason not to do this in C ++ code.
Someone writes, say, a string class and decides to add a translation operator to const char* :
class BadString { public: BadString(const char* s) : mStr(s) { } operator const char*() const { return mStr.c_str(); } bool operator==(const BadString& s) { return mStr == s.mStr; }
Now, someone blindly applies the programming template constant == variable "protective":
BadString s("foo"); if ("foo" == s) // Oops. This compares pointers and is never true. { // ... }
This is IMO, a more insidious problem than random assignment, because you cannot tell from the call site that something is clearly wrong.
Of course, the real lessons are:
- Do not write your own string classes.
- Avoid implicit translation operators, especially when executing (1).
But sometimes you are dealing with third-party APIs that you cannot control. For example, the _bstr_t class, common in Windows COM software, suffers from this drawback.
jamesdlin Jan 26 '10 at 20:39 2010-01-26 20:39
source share