gpt4 book ai didi

c++ - 为什么 std::string 不提供到 char* 的隐式转换?

转载 作者:IT老高 更新时间:2023-10-28 12:55:55 26 4
gpt4 key购买 nike

std::string 提供 const char* c_str ( ) const其中:

Get C string equivalent

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

他们为什么不直接定义operator const char*() const {return c_str();}

最佳答案

来自 C++ 编程语言 20.3.7(重点是我的):

Conversion to a C-style string could have been provided by an operator const char*() rather than c_str(). This would have provided the convenience of an implicit conversion at the cost of surprises in cases in which such a conversion was unexpected.

关于c++ - 为什么 std::string 不提供到 char* 的隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com