Why doesn't std::string provide implicit conversion to char*?

前端 未结 7 1286
滥情空心
滥情空心 2020-11-29 06:14

std::string provides const char* c_str ( ) const which:

Get C string equivalent

Generates a null-terminated sequence of cha

相关标签:
7条回答
  • 2020-11-29 06:31

    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").

    0 讨论(0)
提交回复
热议问题