STL strings are not zero-terminated

In a previous blog post, I listed some advantages (IMHO) of using CString instead of std::string class.

There is another subtle (but important!) point which turns the scales in CString‘s favour: in fact, CString is a C++ class that wraps zero-terminated strings (i.e. the good old C strings), instead it seems that the C++ standard library code wants to pretend that zero-terminated strings do not exist…

Let me show this with a sample code (the full C++ source code is attached to this blog post):


    // Check with CString


    CString str;

    WCHAR * psz = str.GetBuffer(100);

    psz[0] = 0; // …or GetWindowText(hwnd, psz, 100)


    psz = NULL; // psz is no more valid

    assert( wcslen(str) == str.GetLength() ); // OK





    // Check with std::string


    std::wstring s;


    s[0] = 0; // …or GetWindowText(hwnd, &s[0], 100)

    assert( wcslen(s.c_str()) == s.length() ); // BANG!

So, basically, we have a situation in which (assuming ‘s‘ is an instance of std::wstring) s.length() and wcslen(s.c_str()) do not return the same value.

Considering that Windows APIs (like say GetWindowText) work with zero-terminated strings, CString seems to me a clear winner as a convenient string class for C++ Win32 programming.


Leave a Reply

Your email address will not be published. Required fields are marked *