2017-10-20 7 views
0

このコードブロックは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()); 
} 
+1

に置き換えることができますCスタイルの文字列を使用しないで、すでに割り当てを解除したメモリへのポインタを返さないでください。実際、このコードを修正するよりも簡単に開始するのが簡単なのかどうかは確かです。 – milleniumbug

+0

たとえば、コードをどのように変更する必要がありますか?戻り値const_cast (printStream-> str()。c_str()); –

答えて

1

変更が戻りstd::stringのタイプとは直接std::stringオブジェクトを返します。

+0

どうすればいいですか?たとえば、この行をどのように変更できますか? return const_cast (printStream-> str()。c_str()); –

1

私はto_stringという関数が実際にはというのはというstd::stringを返すべきだと思います。

そして、すべてこのジャンクは、変数を変更する*特に* `const_cast`を使用していない、C形式のキャストを使用していない、` new`を使用しないでください

std::string FieldData::to_string() const 
{ return "Invalid Field Type"; } 
関連する問題