string c_str() 释放问题
来源:互联网 发布:linux socket的值 编辑:程序博客网 时间:2024/04/29 06:15
今天遇到一个奇葩问题:
#include <iostream>#include <string>using namespace std;void printStr(const char *s){ cout << "msg:" << s << endl;}int main(){ cout << "------------" << endl; string s1 = "abc"; string s2 = "def"; const char *s = (s1 + s2).c_str(); printStr(s); // 为啥打印不出来 // 因为是指针,指针指向的内容可能已经被释放了。 printStr((s1 + s2).c_str()); return 0;}
结果:
------------
msg:
msg:abcdef
第一个没打印出来。
有啥区别?一个靠形参传进去,一个外面定义一个参数传进去
自信分析,不过是指针指向的东西释放的问题。
#include <iostream>#include <string>using namespace std;void printStr(const char *s){ cout << "msg:" << s << endl;}class Base{public: Base() { m_pValue = new int(10); } ~Base() { delete m_pValue; m_pValue = NULL; } int* value() { return m_pValue; }private: int* m_pValue;};void fun(int *pValue){ cout << "fun: " << *pValue << endl;}int main(){ int *pValue = Base().value(); cout << *pValue << endl; fun(Base().value());// cout << "------------" << endl;// string s1 = "abc";// string s2 = "def";// const char *s = (s1 + s2).c_str();// printStr(s); // 为啥打印不出来// // 因为是指针,指针指向的内容可能已经被释放了。// printStr((s1 + s2).c_str()); return 0;}
0 0
- string c_str() 释放问题
- string.c_str()
- string::c_str()
- string .c_str();
- string.c_str()
- string.c_str()函数说明
- c++ string详解 c_str()
- < C++ > string c_str
- c++ string c_str()
- string的c_str()函数
- c++ string.c_str()小结
- C/C++:string.c_str()
- c_str string 转换成char
- String 类 的c_str()函数
- C string类c_str() 详解
- c_str():string转换成char*
- 透析string的c_str()函数
- string 类成员函数c_str
- matlab与opencv双目相机标定对比
- JOptionPane简介
- 【cocos2dx 3.3 lua】08 随机迷宫生成
- java 操作Redis SortedSet 命令 实例(Jedis) (六)
- 为什么引入非线性激励函数 为什么引入relu
- string c_str() 释放问题
- 风险度量
- 图—搜索——DFS
- 装饰设计模式(Decorator)-IO
- TRF7970 读取二代身份证 ID号 程序 TRF7960A TRF7960 TRF7970A
- 寒假作业
- submit 的4种写法
- HDU
- JPA-2 基本注解