Why wstring :: c_str does not cause a memory leak if not properly removed

Code Segment 1:

wchar_t *aString() 
{
     wchar_t *str = new wchar[5];
     wcscpy(str, "asdf\0");
     return str;
}
wchar_t *value1 = aString();

Code segment 2

wstring wstr = L"a value";
wchar_t *value = wstr.c_str();

If a value is not deleted from code segment 2, a memory leak does not occur. However, if value1 is not deleted from code segment 1, a memory leak occurs. The internal code for wstring :: c_str looks the same to me.

+5
source share
4 answers

An important rule: you should use deletefor everything that was created new, and you should not delete anything.

wstr.c_str() , wstring. , , . delete . , .

aString() , new[], , ( delete[], new[]). , (, string, wstring, ), , .

+11

c_str() wstring. , .

+2

basic_string::c_str() MSDN:

C be, , .

+2

, wstring wchar_t, , wchar_t *, wstring wchar_t * .

+1

All Articles