为什么std :: string不提供隐式转换为char *? [英] Why doesn't std::string provide implicit conversion to char*?

查看:97
本文介绍了为什么std :: string不提供隐式转换为char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


获取C字符串等效

Get C string equivalent

生成以字符串对象的相同
为内容的字符(c-string)的以null结束的序列

将其作为指向
字符数组的指针返回。

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.

为什么不只是定义运算符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()提供的。这将提供方便的隐式转换以惊喜为代价,在这种转换是意外的情况下。

这篇关于为什么std :: string不提供隐式转换为char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆