I have an immutable wstring implementation of my own, however I have a problem when actually using it.When I need the wchar array I need it null-terminated, so I do this:
wchar* String::CStr() const
{
wchar* temp = new wchar[size + 1];
for(int i = 0; i < size; i++)
{
temp[i] = data[i];
}
temp[size] = L'\0';
return(temp);
}
Now this is good and all, but I have no way of releasing the newly created wchar array, so there's a memory leak each time CStr() is used.So instead I tried using an automatic pointer to fix it:
Auto<wchar> String::CStr() const
{
wchar* temp = new wchar[size + 1];
for(int i = 0; i < size; i++)
{
temp[i] = data[i];
}
temp[size] = L'\0';
return(Auto<wchar>(temp));
}
Auto just stores the wchar* and deletes it in the destructor.Of course it didn't work at all, since the Auto<> dies at the end of the function so I get an empty wchar*.Also, since Auto<> has a destructor, this method NEVER gets inlined.So I'm in a totally wrong direction.I tried looking around std::wstring source, however it's pretty unreadable with all the internal typedefs, what I noticed is that it doesnt just store something like my wchar* data, but also a wchar* that I assume is jut 1 character(the null terminator):
_Elem *_Myptr; // pointer to allocated string
_Elem _Nul; // nul terminator for unallocated string
However it doesn't relaly use _Nul in the method, it just returns _Myptr:
const _Elem *__CLR_OR_THIS_CALL c_str() const
{ // return NTBS
return (_Myptr != 0 ? _Myptr : &_Nul);
}
However I don't see where is _Myptr being null terminated prior to being returned?Or are they just throwing it out in its raw state?