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

前端 未结 7 1355
滥情空心
滥情空心 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:20

    I see at least two problems with the implicit conversion:

    • Even the explicit conversion that c_str() provides is dangerous enough as is. I've seen a lot of cases where the pointer was stored to be used after the lifetime of the original string object had ended (or the object was modified thus invalidating the pointer). With the explicit call to c_str() you hopefully are aware of these issues. But with the implicit conversion it would be very easy to cause undefined behavior as in:

      const char *filename = string("/tmp/") + name;
      ofstream tmpfile(filename); // UB
    • The conversion would also happen in some cases where you wouldn't expect it and the semantics are surprising to say the least:

      string name;
      if (name) // always true
       ;
      name-2; // pointer arithmetic + UB
      These could be avoided by some means but why get into this trouble in the first place?

提交回复
热议问题