开发者

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 understand开发者_StackOverflow中文版ing 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;
}


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();
}


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


The return value of .c_str() is owned by wstr. When wstr is destructed at the end of the function, p becomes an invalid pointer.


LPCWSTR is a pointer to a bunch of wchar_ts. You are returning a pointer that points to a local variable (wss) - a variable that doesn't exist after your function returns. Thus your pointer means nothing and points to garbage.

You should return a std::wstring instead, because it holds the string data, not just a pointer.

Something like:

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

[edit] though, personally i would do this using _itow() for performance reasons as Simon Mourier suggests.


You should use the _itoa, _i64toa, _ui64toa, _itow, _i64tow, _ui64tow runtime provided functions (or the secure ones if security is a concern).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜