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

2022-01-07 00:00:00 string c++ stl

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

获取等效的 C 字符串

Get C string equivalent

生成一个空终止序列具有相同的字符(c 字符串)内容作为字符串对象和将其作为指向数组的指针返回字符.

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.

返回的数组指向一个具有所需的内部位置这个序列的存储空间字符加上它的终止空字符,但此中的值不应该在数组中修改计划并且只被授予留在在下一次调用 a 之前保持不变的非常量成员函数字符串对象.

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();}?

Why don't they just define operator const char*() const {return c_str();}?

推荐答案

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

From the C++ Programming Language 20.3.7 (emphasis mine):

C 样式字符串的转换可以由运算符 const char*() 而不是 c_str() 提供.这将提供隐式转换的便利但代价是在这种转换是意外的情况下.

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.

相关文章