Question

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?

Was it helpful?

Solution

You could store null terminated string in your data array, and just return it as const wchar *. It would eliminate the unneeded copying of data.

Edit:

About extra wchar pointer in the wstring source you mentioned. It is probably the end() pointer. The implementation allocates some data buffer where to store the string, but the allocated buffer is larger then the string, so it stores the pointer to the beginning of the buffer (data) and the pointer to the end of data ( to the '\0' wchar) . This way the size() function can be easily implemented as int size() const{ return end_ptr-data; } and works even if wstring contains \0 by itself.

OTHER TIPS

_Myptr is null terminated, so there is no need to add the terminator when _Myptr is returned by c_str.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top