std::string
provides const char* c_str ( ) const which:
Get C string equivalent
Generates a null-terminated sequence of cha
I addition to the rationale provided in the specification (unexpected surprises), if you're mixing C API calls with std::string
, you really need to get into the habit of using the ::c_str()
method. If you ever call a varargs function (eg: printf
, or equivalent) which requires a const char*
, and you pass a std::string
directly (without calling the extraction method), you won't get a compile error (no type checking for varargs functions), but you will get a runtime error (class layout is not binary identical to a const char*
).
Incidentally, CString
(in MFC) takes the opposite approach: it has an implicit cast, and the class layout is binary-compatible with const char*
(or const w_char*
, if compiling for wide character strings, ie: "Unicode").