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* 的隐式转换?


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01