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
原创粉丝点击