1

私のプロジェクトでは、ファイル名を指定してテクスチャをロードするために使用します。ここで、 sconst char* app_dir(std::string fileToAppend);を返し、アプリケーション名を。で変更するこの関数を作成しました。char *では文字列操作を簡単にすることができないので、を使用します。私のテクスチャローダーはファイル名にconstchar*を使用するため、c_str()に戻す必要があります。これで、ASCIIシンボル文字のシーケンスが生成されます(バグ)。のリターンタイプをに変更することで、すでに問題を修正しています。しかし、なぜそれが起こっているのですか?mainargv[0]fileToAppendstd::stringapp_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に変更することで、すでに機能しているものがあります。

4

2 に答える 2

1

大したことはありません:)ローカルオブジェクトへのポインタを返す

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() を使用します

于 2013-03-16T13:23:32.853 に答える
1

関数const char* app_dir(std::string fileToAppend);を使用する場合 スタックに割り当てられ、関数の終了時に既に削除されているメモリへのポインターを取得します。

于 2013-03-16T13:08:03.037 に答える