2010-06-07 43 views

回答

12

你可以做wstringstream.str().c_str()as DeadMG writes。但是,該調用的結果僅在表達式的生命週期結束時纔有效,這是該表達式的一部分。

具體地,該

const LPCWSTR p = wss.str().c_str(); 
f(p); // kaboom! 

將不起作用,因爲wstringstream.str()返回一個臨時對象和.c_str()返回一個指針到該對象,並在分配的結束該臨時對象將被破壞。

你可以做的,而不是要麼

f(wss.str().c_str()); // fine if f() doesn't try to keep the pointer 

const std::wstring& wstr = wss.str(); // extends lifetime of temporary 
const LPCWSTR p = wstr.c_str(); 
f(p); // fine, too 

因爲綁定到const引用臨時對象都會有自己的壽命延長了參考的一生。

+0

或者,如果分配給一個常量引用,則引用的生存期爲 – 2010-06-07 17:41:32

+0

@Greg:我剛剛正在編寫這個過程。 ':'' – sbi 2010-06-07 17:44:36

+0

我認爲你的第二個代碼不好,因爲C++可以在調用'f'之前銷燬臨時文件。這真的發生在我身上一次!所以你不能存儲'c_str()'或'data()'的結果。 – Philipp 2010-06-07 19:47:33

0

wstringstream.str().c_str();