const char * 和 std::string.c_str()是个危险的东西! | JXITC Studio
const char * 和 std::string.c_str()是个危险的东西!
今天中招了!
有一个类,内部有个 const char * 类型的变量 word, 该类构造函数用一个string来初始化word,于是我想都没想就这么写:
1 | MyClass(std::string inputStr){ |
2 | this ->word = inputStr.c_str(); |
哪知道!这是个陷阱!以前一直都没意识到,c_str()就返回一个地址而已,而这个地址可能会随着string 对象的销毁(比如局部对象啊,或者显示引用delete)而变得无效!!
众所周知,(其实我也就上周才知道。。。), std::string内部是有一个char buffer 指针的存在的,用来实际存储这个string的内容,而c_str()无非就是把这个内部的东西返回到外部而已。
而const char *也不就是个指针么,老老实实指着 c_str() 返回来的东西,结果不想那块地址会被删除!
我现在的解决方法是这么做咯:
02 | string *a = new string( "abc" ); |
05 | char *cha = new char [a->size() + 1]; |
06 | memcpy (cha,a->c_str(),a->size() + 1); |
今天又包了一下,包了个很好看的函数,以后可以直接赋值过来用:
01 | inline char * getCharPtr(string &str){ |
04 | char *cha = new char [str->size() + 1]; |
05 | memcpy (cha,str->c_str(),str->size() + 1); |