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

2024-05-11C/C++开发问题
3

本文介绍了为什么 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* 的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6