zoukankan      html  css  js  c++  java
  • const char * 和 std::string.c_str()是个危险的东西!

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

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

    今天中招了!

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

    1MyClass(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() 返回来的东西,结果不想那块地址会被删除!

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

    01void 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}

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

    01inline 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}
  • 相关阅读:
    最后完整的excel.java文件
    *将制定类型的List写入Excel中
    初始化Excel表格
    单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等
    生成写入excel
    activity_daochu.xml代码
    设计了activity_daochu.xml
    个人作业第二阶段
    阅读笔记一-1软件=程序+软件工程
    每日总结
  • 原文地址:https://www.cnblogs.com/lexus/p/2857635.html
Copyright © 2011-2022 走看看