const char* getOutPath()
{
return classVarStr.c_str();
}
我有以前的功能,
当我收到返回值时有一些奇怪的东西,
我得到了完整的路径,但不包括第一个字符!
所以如果路径是results/appName_subStr.dat
我得到esults/appName_subStr.dat
!
我将函数调用更改为
string getOutPath()
{
return classVarStr;
}
然后我c_str()
在收到值后调用以使第一个路径正确char
我猜测它可能会发生,因为函数堆栈弹出可能以某种方式修改了地址?
任何人都遇到过类似的问题,可能是什么原因?
编辑:
class X
{
private:
string classVarStr;
public:
X(string in) : classVarStr(in)
const char* getOutPath()
{
return classVarStr.c_str();
}
string getOutPathStr()
{
return classVarStr;
}
}
class B
{
private:
X xinstance;
public:
B(int argc, char * argv[])
{
getSomepathFn(argc, argv);
}
string getAppPath1()
{
return xinstance.getOutPath(); // this create a string then pass a copy, and internally deleted
}
const char * getAppPath2()
{
return xinstance.getOutPathStr().c_str();// this is a problem, create a string, then pass const to the data, and deleted before the function call return, **Undefined behaviour** because the `getOutPathStr()` doesnt return a const reference
}
}
class appObj
{
void printMessage()
{
B obj = getBObj();
FILE *fileptr = fopen(obj->getAppPath2(), "a");// this is the faulty area
}
};