I thought buf should be destroyed right after function return, so the
pointer &buf[0]
might be invalid.
Your thoughts are 100% correct.
But it seems work fine, how does it work?
It "works" because the part of the call stack that holds the buf
array just happened to not have its contents written over by the time you actually use it.
But this is undefined behavior, and undefined behavior means anything can happen, and that can include "summoning an Armageddon" and/or "working just fine". You just got lucky this time.
And is it a fine design?
No, it's a terrible design. Fortunately it has a simple fix: just return the std::wstring
itself.
std::wstring GetString(HINSTANCE hInstance, UINT SID)
{
wchar_t buf[2048] = {0};
LoadStringW(hInstance, SID, buf, sizeof(buf)/sizeof(wchar_t));
return std::wstring(buf);
}
void SomeWork()
{
std::wstring str = GetString(hInst, 123);
}
All non-stupid C++ compilers will optimize away the temporaries in this case, so this code has no performance penalty in practice. In fact, the Visual C++ compilers will optimize this case even when you turn off all optimizations.
This specific optimization is called return value optimization (RVO). If your C++ compiler doesn't do RVO even when set at its highest optimization level, get another one.