このコードブロックはstrstream
と書かれています。そして、それを以下のようにsstream
に変換しました。私は確信していませんが、printStream->str()
はprintStream
で指されるストリームバッファ内の内容のコピー(一時的)を持つ文字列オブジェクトを返していると思うし、c_str()
を呼び出してconst char *
を呼び出してキャストしていますその関数のスコープの外側にポインタを戻します。私はそれが一時的な値printStream->str()
から戻ってきているので、あなたはこの機能の外に割り当て解除されたメモリへのポインタを使用していると思います。私はこれをどのようにするべきですか?strstreamをsstreamのコンストレイントに変換するc_str()
char * FieldData::to_string() const
{
if(printStream)
return printStream->str();
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostrstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << '\0';
return printStream->str();
}
char * FieldData::to_string() const
{
if(printStream)
return const_cast<char *>(printStream->str().c_str());
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostringstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << '\0';
return const_cast<char *>(printStream->str().c_str());
}
に置き換えることができますCスタイルの文字列を使用しないで、すでに割り当てを解除したメモリへのポインタを返さないでください。実際、このコードを修正するよりも簡単に開始するのが簡単なのかどうかは確かです。 – milleniumbug
たとえば、コードをどのように変更する必要がありますか?戻り値const_cast(printStream-> str()。c_str()); –