0

から への変換中に奇妙な動作に遭遇したとき、私はいくつかの文字列で遊んでいstd::stringましたLPCSTR

デモ用に小さなテスト アプリケーションを作成しました。

#include <string>
#include <Windows.h>
#include <iostream>

using namespace std;

int main ()
{
    string stringTest = (string("some text") + " in addition with this other text").c_str(); 
    LPCSTR lpstrTest= stringTest.c_str();
    cout << lpcstrTest << '\n';

    cout << (string("some text") + " in addition with this other text").c_str() << '\n';

    LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();
    cout << otherLPSTR;
}

そして、ここに出力があります:

some text in addition with this other text
some text in addition with this other text
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ...[more unreadable stuff]...

この奇妙な動作の原因は何なのか、ただただ疑問に思っています。

ありがとうございました

4

3 に答える 3

2
LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();
cout << otherLPSTR;

一部

 (string("some text") + " in addition with this other text")

いわゆる「一時的な」オブジェクトを作成します。これには名前がなく、それを含むステートメントが終了すると破棄されます。そこから c_str() を取得します。これは、その一時オブジェクトの内部ストレージを指します。その c_str() を otherLPCSTR 変数に割り当てます。その後、「一時文字列を含むステートメント」が終了したため、一時文字列が破棄され、他の LPCSTR は「どこにも」ポイントしません。

于 2012-07-06T22:48:29.627 に答える
0

式によって作成された一時オブジェクトは、完全な式の評価が完了するまで存続します。完全な式が評価されると、その一時変数はすべて自動的に破棄されます。

これが起こることです

LPCSTR otherLPCSTR = 
  (string("some text") + " in addition with this other text").c_str();

このステートメントの直後にテンポラリが破棄され、最終的otherLPCSTRにデッド メモリを指します。

最初のケースでstringTestは、一時的なものではありません。の最後まで存続します。mainつまり、lpstrTestポインターは有効なままです。

2 番目のケースでは、一時std::stringオブジェクトがまだ生きている間、すぐに出力に使用されます。

3 番目のケースでのみ、上記のように無効になるポインターを格納しようとしています。

于 2012-07-06T22:48:57.850 に答える
0

によって返されるポインターはc_str()、その文字列オブジェクトが有効である限り有効です。

// A copy of a temporary string is made here. The temporary is destructed 
// but stringTest stays in scope until the end of main
string stringTest = (string("some text") + " in addition with this other text").c_str();

LPCSTR lpstrTest= stringTest.c_str();
cout << lpcstrTest << '\n';

// the temporary is in scope until the end of the full expression, so this is fine.

cout << (string("some text") + " in addition with this other text").c_str() << '\n';

// But this isn't. At the end of the line, the temporary string object is long gone.
// otherLPCSTR now points to deallocated memory.
LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();

// And here you're accessing that memory.
cout << otherLPSTR;
于 2012-07-06T22:51:32.733 に答える