.c_str () weirdness? Changing data without rhyme or reason?

I have this simple function:

const wchar_t *StringManager::GetWCharTStar(int stringId)
{
    std::wstring originalString = StringManager::GetString(stringId);
    const wchar_t *retStr = originalString.c_str();
    return retStr;
}

In the second line of this function, I have the correct wchar_t *. However, when I return, the data switches to junk data. There are no functions between them. What gives?!

+3
source share
5 answers

originalString is allocated on the stack. The .c_str () method simply returns a pointer to some contiguous internal memory of the wstring object. When the function returns, originalString goes out of scope and is destroyed, so the pointer value you return indicates the memory to be deleted.

, , new malloc(), /() .

+11

. originalString , , , .

+5

std::wstring originalString; - GetWCharTStar.

GetWCharTStar(), , , , .

:

const wchar_t *StringManager::GetWCharTStar(int stringId)
{
    const std::wstring& originalString = StringManager::GetString(stringId);
    const wchar_t *retStr = originalString.c_str();
    return retStr;
}

, StringManager::GetString() :

const std::wstring& StringManager::GetString(int stringId);

, , , StringManager, . , StringManager std::vector, , , , , .

, .

+3

The previous answers are mostly correct, with the exception of one small detail. You do not return a pointer to the destroyed object, you return a pointer belonging to the destroyed object. When this object was destroyed, the object pointed to by the pointer was also destroyed.

+1
source

This is a FAQ. You are returning a pointer to the object that is being freed (the originalString object) before you can actually use it.

0
source

Source: https://habr.com/ru/post/1724973/


All Articles