Returns LPCWSTR from a function?

To pass an integer value to SetWindowTextW (), (I use the unicode assembly, in C ++, from Visual Studio 2010), can this function return LPCWSTR? I am pretty sure that I don’t understand something here because it returns a strange value. I know that LPCWSTR is a long string with long pointers with a null character, 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; } 
+4
source share
6 answers

There is nothing wrong with returning LPCWSTR from a function. A common problem that arises is managing the memory around the return value. A LPCWSTR usually contained in allocated memory, so ownership of this memory must be understood between the caller and the callee.

I do not want to select your sample, but this is a good example of what might go wrong with the return of LPCWSTR . The memory for the string is stored by the wss instance, which is local to this function. As soon as the function returns the memory, it is freed in the wss destructor and, therefore, the return value is invalid.

If you are already using C ++, my recommendation would be to simply return std::string or wstring to eliminate 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 problem, return it by reference.

 void int2LPCWSTR ( int integer, wstring& value ) { wstringstream wss; wss << integer; value = wss.str(); } 
+8
source

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

+2
source

The return value .c_str() belongs to wstr . When wstr destroyed at the end of a function, p becomes an invalid pointer.

0
source

LPCWSTR is a pointer to a bunch of wchar_t s. You are returning a pointer pointing to a local variable ( wss ) - a variable that does not exist after the function returns. So your pointer means nothing and points to trash.

Instead, you should return std::wstring because it contains string data, not just a pointer.

Sort of:

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

[edit], although I personally did this with _itow () for performance reasons, as suggested by Simon Murrier.

0
source

You must use the _ itoa, _i64toa, _ui64toa, _itow, _i64tow, _ui64tow executable functions (or safe if security is a problem).

0
source
 LPWSTR int2LPCWSTR(const int & v) { LPWSTR buffer = new wchar_t[100]; _itow_s(v, buffer, 100, 10); return buffer; } 
0
source

All Articles