In the following scenario:
struct Foo
{
// ...
operator Bar() {... } // implicit cast to Bar
}
Foo GetFoo() { ... }
void CallMeBar(Bar x) { ... }
// ...
It will survive, but relying in that fact may be confusing, and may cause clients of your code to reach for the C++ Standard, ask questions on Stack Overflow, etc ;-). For instance what happens when someone does:
Bar b = GetFoo();
CallMeBar(b);
This time, the Foo has gone before CallMeBar is called, but most programmers would want conversions to create an independent object, and hence for the code to behave the same as:
CallMeBar(GetFoo());
This is why std::string
does not have an implicit cast to char*
, unlike CString
's cast to LPCTSTR
. Instead, std::string
has the c_str()
member function, which has the same constraint but makes it a bit more obvious in calling code that it's not a real conversion:
CallMePtr(GetString().c_str()); // OK
char* p = GetString().c_str(); // Bad
CallMePtr(p); // Badness manifests
const string &s = GetString(); // use "the most important const"
CallMePtr(s.c_str()); // Best be on the safe side