Why does std::string not provide a conversion to const char*?

前端 未结 4 1385
小鲜肉
小鲜肉 2020-12-03 11:30

This is more of a policy or a historical question. Why was it decided not to provide a const char * conversion for std::string? Were there a fear someone might do p

4条回答
  •  温柔的废话
    2020-12-03 12:11

    The string class internally need not store the string with a terminating 0. In fact it doesn't even have to store them in contiguous memory if it didn't want to. Therefore an implicit cast doesn't make sense, since it may be a costly operation.

    The c_str() function then gives you the c-string. Depending on how the library stores it internally this function may have to create a temporary. This temporary is only valid until you modify the string.

    It is unfortunately however since a string could just been specified to be a c-string internally. This wouldn't lead to any loss of functionality and would allow an implicit conversion.

    Edit The standard does basically imply the memory is contiguous (if accessed through data() or the [] operator), though it need not be internally, and certainly not null terminated. Likely all implementations store the 0 as well. If this were standardized then the implicit conversion could be safely defined.

提交回复
热议问题