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

标签 c++ string stl

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/

相关文章:

php - 如何在 PHP 中拆分 * 和 - 上的字符串?

c++ - 什么是 std::mbstate_t?

c++ - 多重集 lower_bound 迭代器的位置

c++ - 加权有向图中从节点返回自身的最短距离

c++ - 为什么字符串对象需要 #include <string> 而不是字符串文字?

c++ - 无法在动态链接库 libstdc++-6.dll 中找到过程入口点 __gxx_personality_v0

java - 如何计算字符串数组中字符串的重复次数

algorithm - C++ std::unordered_map 键自定义散列

c++ - 使用 C++ 和 QWT 移动图形

c++ - 轻松测量耗时