没有躲过的坑--string中的c_str()陷阱

string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

c_str函数的返回值是const char*的,不能直接赋值给char*,所以就需要我们进行相应的操作转化。

#include <iostream>  
#include <string>  
int main() {  
    std::string s = "Chelse";  
    const char *str = s.c_str();  
    std::cout << str << std::endl;  
    s[1] = 'm';  
    std::cout << str << std::endl;  

    return 0;  
} 

第一个输出 当然是 Chelse;
第二个输出呢: Chelse还是Cmelse呢?
答案是Cmelse。
const char*的值应该是个常量啊,怎么还能改变值呢?
这就是很多人遇到的坑儿,也许面试的时候你会顺利的回答出来,但是在实际的工程中,往往掉进坑儿里,难以自拔。
const char*, char const*, char* const的区别是什么?老
const char*与char const*是等价的,指的是指向字符常量的指针,即指针可以改变指向但其指向的内容不可以改变。
而char* const相反,指的是常量指针,即指向不可以改变但指针指向的内容可以改变。因此这里的const char*指向的内容本类是不可以改变的。

那么这里为什么改变了呢?这跟str这个const char*的生命周期及string类的实现有关,string的c_str()返回的指针是由string管理的,因此它的生命期是string对象的生命期,而string类的实现实际上封装着一个char*的指针,而c_str()直接返回该指针的引用,因此string对象的改变会直接影响已经执行过的c_str()返回的指针引用。

看下官方说法:

const charT* c_str() const;
Returns: A pointer to the initial element of an array of length size() + 1 whose first size() elements equal the corresponding elements of the string controlled by *this and whose last element is a null character specified by charT().
Requires: The program shall not alter any of the values stored in the array. Nor shall the program treat the returned value as a valid pointer value after any subsequent call to a non-const member function of the class basic_string that designates the same object as this.

简而言之,调用任何 std::string 的非 const 成员函数以后,c_str() 的返回值就不可靠了。

  • 10
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值