在我的项目中,我使用指定它的文件名来加载纹理。现在,我创建了一个函数const char* app_dir(std::string fileToAppend);,它返回main的argv[0]并通过fileToAppend更改应用程序名称。因为我不能用char*简化字符串操作,所以我使用了std::string。我的纹理加载器使用一个const *作为文件名,因此需要切换回c_str(),现在它生成了一系列的ASCII符号字符(bug)。我已经通过将app_dir()的返回类型更改为std::string来解决这个问题。但为什么会这样呢?
编辑
样本代码:
//in main I did this
extern std::string app_filepath;
int main(int argc, char** arv) {
app_filepath = argv[0];
//...
}
//on other file
std::string app_filepath;
void remove_exe_name() {
//process the app_filepath to remove the exe name
}
const char* app_dir(std::string fileToAppend) {
string str_app_fp = app_filepath;
return str_app_fp.append(fileToAppend).c_str();
//this is the function the generates the bug
}正如我前面所说的,通过将其返回类型更改为std::string,我已经有了该函数。
发布于 2013-03-16 13:08:03
当您使用函数、const* app_dir(std::string fileToAppend);时,您将得到指向在堆栈上分配并在函数结束时已经删除的内存的指针。
发布于 2013-03-16 13:23:32
返回指向本地对象的指针
return str_app_fp.append(fileToAppend).c_str();将功能更改为
std::string app_dir(const std::string& fileToAppend) {
string str_app_fp = app_filepath + fileToAppend;
return str_app_fp;}
在返回值上使用c_str()
https://stackoverflow.com/questions/15449544
复制相似问题