const char * 和 std::string.c_str()是个危险的东西!

今天中招了!

有一个类,内部有个 const char * 类型的变量 word, 该类构造函数用一个string来初始化word,于是我想都没想就这么写:

1 MyClass(std::string inputStr){
2   this->word = inputStr.c_str();
3 }

哪知道!这是个陷阱!以前一直都没意识到,c_str()就返回一个地址而已,而这个地址可能会随着string 对象的销毁(比如局部对象啊,或者显示引用delete)而变得无效!!

众所周知,(其实我也就上周才知道。。。), std::string内部是有一个char buffer 指针的存在的,用来实际存储这个string的内容,而c_str()无非就是把这个内部的东西返回到外部而已。

而const char *也不就是个指针么,老老实实指着 c_str() 返回来的东西,结果不想那块地址会被删除!

我现在的解决方法是这么做咯:

01 void constchartest(){
02     string *a = new string("abc");
03  
04     //define a new memory space for saving this char array
05     char *cha = new char[a->size() + 1];
06     memcpy(cha,a->c_str(),a->size() + 1);
07  
08     const char *p = cha;    //point to this new allocated  memory
09  
10     delete a;   //OK now p is irrelevant with a, never mind if a is deleted
11     cout << p << endl;
12 }

 

今天又包了一下,包了个很好看的函数,以后可以直接赋值过来用:

01 inline char * getCharPtr(string &str){
02  
03     //define a new memory space for saving this char array
04     char *cha = new char[str->size() + 1];
05     memcpy(cha,str->c_str(),str->size() + 1);
06  
07     const char *p = cha;    //point to this new allocated  memory
08  
09     return p;
10 }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值