Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning LPCWSTR from a function?

In order to pass an integer value to SetWindowTextW(), (I am using a unicode build, in C++, with Visual Studio 2010), would this function suffice return an LPCWSTR? I'm pretty sure there is something I am not understanding here, because it returns a strange value. I know that an LPCWSTR is a null terminated long pointer wide character string, but I still think I'm missing something!?

const LPCWSTR int2LPCWSTR ( int integer )
{
 wstringstream wss;
 wss << integer;
 const wstring& wstr = wss.str();
 const LPCWSTR p = wstr.c_str();
 return p;
}
like image 708
rem45acp Avatar asked Dec 07 '10 17:12

rem45acp


2 Answers

There is nothing wrong in itself with returning an LPCWSTR from a function. The general problem that arises though is the memory management around the return value. A LPCWSTR is typically held in allocated memory so ownership of that memory needs to be understood between the caller and callee.

I don't want to pick on your sample but it is a good example of what can go wrong with returning an LPCWSTR. The memory for the string is held by the wss instance which is local to the function. As soon as the function returns the memory is freed in the destructor of wss and hence invalidates the return value.

If you're already using C++ my recomendation would be to just return the std::string or wstring directly to eliminate the confusion about who owns the allocated memory.

wstring int2LPCWSTR ( int integer )
{
 wstringstream wss;
 wss << integer;
 return wss.str();
}

Or if copying the value around is a concern return it by reference.

void int2LPCWSTR ( int integer, wstring& value )
{
 wstringstream wss;
 wss << integer;
 value = wss.str();
}
like image 106
JaredPar Avatar answered Sep 16 '22 14:09

JaredPar


You can't.
Return wstring, and then use c_str() to get LPCWSTR and pass it to SetWindowTextW

like image 32
Abyx Avatar answered Sep 17 '22 14:09

Abyx