Why doesn#39;t std::string provide implicit conversion to char*?(为什么 std::string 不提供到 char* 的隐式转换?)
问题描述
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.
这篇关于为什么 std::string 不提供到 char* 的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::string 不提供到 char* 的隐式转换?


- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07