C++中return作用于s.c_str()时返回结果出现乱码,该怎么处理
C++中return作用于s.c_str()时返回结果出现乱码
我的问题:(在VC++6.0下)
1. cout<<pstrcatEx(c11, c12)<<endl;为什么在两种模式下结果不一样
2. pstrcatEx和pstrcatEx2执行的代码本质是相同的,为什么结果不同
------解决方案--------------------
第二个和第三个函数都返回了本地string的c_str,在函数返回后这个string对象会析构,它的c_str是未定义的行为。
- C/C++ code
#include <iostream> #include <string> using namespace std; string strcatEx(const char *c1, const char *c2) { string s1="",s2=""; if(c1) s1=c1; if(c2) s2=c2; return (s1+s2); } const char *pstrcatEx(const char *c1, const char *c2) { string s=strcatEx(c1, c2); return s.c_str(); } const char *pstrcatEx2(const char *c1, const char *c2) { string s1="",s2=""; if(c1) s1=c1; if(c2) s2=c2; string s=s1+s2; return s.c_str(); } int main(int argc, char* argv[]) { char *c11="a12",*c12="a21a"; cout<<strcatEx(c11, c12)<<endl; cout<<strcatEx(c11, c12).c_str()<<endl; cout<<pstrcatEx(c11, c12)<<endl; cout<<pstrcatEx2(c11, c12)<<endl; return 0; } //运行结果: //VC++6.0 Debug cout<<strcatEx(c11, c12)<<endl; // a12a21a cout<<strcatEx(c11, c12).c_str()<<endl; // a12a21a cout<<pstrcatEx(c11, c12)<<endl; //葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺 cout<<pstrcatEx2(c11, c12)<<endl; //葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺 //VC++ 6.0 Release cout<<strcatEx(c11, c12)<<endl; // a12a21a cout<<strcatEx(c11, c12).c_str()<<endl; // a12a21a cout<<pstrcatEx(c11, c12)<<endl; // a12a21a cout<<pstrcatEx2(c11, c12)<<endl; //(一个笑脸标志)8 //C-Free(MinGW5) Debug/Release cout<<strcatEx(c11, c12)<<endl; // a12a21a cout<<strcatEx(c11, c12).c_str()<<endl; // a12a21a cout<<pstrcatEx(c11, c12)<<endl; // a12a21a cout<<pstrcatEx2(c11, c12)<<endl; // a12a21a //strcatEx(c11, c12).c_str();正常,说明不是c_str()的问题 //VC++6.0下通过调试和设置输出发现: string s=strcatEx(c1, c2); //正常 string s=s1+s2; //正常 s.c_str(); //正常 //出现问题的地方应该是 return 作用于 s.c_str() 时, //返回的const char *pstrcatEx和const char *pstrcatEx2不正常
我的问题:(在VC++6.0下)
1. cout<<pstrcatEx(c11, c12)<<endl;为什么在两种模式下结果不一样
2. pstrcatEx和pstrcatEx2执行的代码本质是相同的,为什么结果不同
------解决方案--------------------
第二个和第三个函数都返回了本地string的c_str,在函数返回后这个string对象会析构,它的c_str是未定义的行为。