The answers to your specific problems can be found in both the good answers provided. Since the question title was simply wstring::c_str() contains garbage
I'm going to point out a way to get a result that is correct without the decode
function.
Microsoft added a number of ATL conversion macros and classes to convert between wide character (Unicode) and MBCS (Ascii). They are available on VS2008. The supported conversions can be found in the MSDN Documentation:
ATL 7.0 introduces several new conversion classes and macros, providing significant improvements over the existing macros. The names of the new string conversion classes and macros take the form:
CSourceType2[C]DestinationType[EX].
[snip]
SourceType/DestinationType
A = ANSI character string.
W = Unicode character string.
T = Generic character string (equivalent to W when _UNICODE is defined, equivalent to A otherwise).
OLE = OLE character string (equivalent to W).
The [EX]
is optional and often used if you don't want to specify the size of the default internal buffer that gets used with the macro.
In your case the conversion macro CA2W
(convert Ascii to Widechar) should do what you want. You only need to #include <atlbase.h>
to use them. These macros take 2 parameters - the string to be converted and the code page (defaults to CP_ACP if not specified)
In your case you had:
std::wstring res = decode(src);
const wchar_t *result = res.c_str();
Using the ATL conversion macros you could do it this way:
std::wstring res = CA2W(src, CP_ACP);
const wchar_t *result = res.c_str();
Since the macros default to Ansi Code Page you can also leave off CP_ACP like this:
std::wstring res = CA2W(src);
const wchar_t *result = res.c_str();
Regarding the issue with the temporary objects the same thing applies to the class returned by these macros. Microsoft even documents this issue with an incorrect usage example in the link provided earlier:
// Example 3
// Incorrect use of conversion macros.
void ExampleFunction3(LPCWSTR pszW)
{
// Create a temporary instance of CW2A,
// save a pointer to it and then delete
// the temportary instance.
LPCSTR pszA = CW2A(pszW);
// The pszA in the following line is an invalid pointer,
// as the instance of CW2A has gone out of scope.
ExampleFunctionA(pszA);
}