2017-01-09 137 views
0

我想在我的第一個MFC應用程序中顯示一條簡單消息。MFC - 顯示消息

奇怪的是,第一個樣本不起作用,而第二個樣本正常工作。

auto text = std::to_wstring(1).c_str(); 
MessageBox(text, NULL, 0); // Not ok, the message is empty 

auto temp = std::to_wstring(1); 
MessageBox(temp.c_str(), NULL, 0); // Ok, display 1 

你能解釋爲什麼這種行爲?

+0

可能重複的[std :: string :: c \ _str()和臨時表達式](http://stackoverflow.com/questions/10006891/stdstringc-str-and-temporaries) – IInspectable

回答

4

是的,在第一個示例中,通過調用std :: to_wstring創建的wstring只包含該行的範圍。該行執行後,它超出範圍,其值是可疑的。

在第二個示例中,wstring仍處於作用域中,因此對.c_str()的調用起作用。

不,其他答案是錯誤的。看看c_str()的執行情況。 c_str()基本上返回LPCWSTR ......稱之爲const WCHAR*const wchar_t*或其他。但是,c_str()的返回是指向wstring的內部指針。問題是在執行代碼行後,從to_wstring()返回的wstring無效,因此c_str()返回的指針是垃圾。爲了好玩,試試下面的代碼:

//cstr_.cpp 
#include <iostream> 
#include <string> 

using namespace std; 

int main(int argc, char* argv) 
{ 
    auto temp = to_wstring(1).c_str(); 
    wprintf(L"%s\n", temp); 

    auto temp2 = to_wstring(1); 
    wprintf(L"%s\n", temp2.c_str()); 

    wstring ws = to_wstring(1); 
    auto temp3 = ws.c_str(); 
    wprintf(L"%s\n", temp3); 
} 

我編譯上述從VC++ shell提示:cl.exe時cstr.cpp

如果對方的回答是正確的,那麼最後一行應該有垃圾或沒有輸出,因爲根據另一個答案,c_str()是一個溫度。但是,如果我的答案是正確的,那麼它應該輸出1(它的確如此)。如果一切都失敗了,請查看實現源代碼。

+0

問他如何引用臨時如果它仍在範圍內,則由to_wstring()創建。 –

+1

@bit:[臨時對象生命週期](http://en.cppreference.com/w/cpp/language/lifetime#Temporary_object_lifetime)。 – IInspectable

+0

@IInspectable:非常感謝。現在可以了。你是對的。再次感謝你。 – bit