std::wstring originalString;
is a local variable inside the body of your GetWCharTStar
function.
As soon as you leave the scope of the GetWCharTStar()
function, this local variable gets destroyed and the pointer you return is no more valid.
The following code might eventually work:
const wchar_t *StringManager::GetWCharTStar(int stringId)
{
const std::wstring& originalString = StringManager::GetString(stringId);
const wchar_t *retStr = originalString.c_str();
return retStr;
}
Provided StringManager::GetString()
returns a reference:
const std::wstring& StringManager::GetString(int stringId);
However, this is still risky as it assumes the strings managed by your StringManager
class will never be relocated in memory. For example, if StringManager
is implemented with the help of an std::vector
then as soon as the vector needs to expand, its previous content gets copied elsewhere in a larger memory block and you end up holding a reference to an object that is no more there.
In other words, avoid returning handles to internal data.