STL strings: loading from resources

As we’ve already seen, while it is possible to load CString’s from resources out of the box, std::string and std::wstring classes do not offer this feature.

Carefully reading the MSDN documentation for LoadString Win32 API, an interesting point about nBufferMax parameter can be found:

If this parameter is zero, then lpBuffer receives a read-only pointer to the resource itself.

We can use this particular feature of LoadString to write a simple C++ function to load std::wstring’s from resources:


std::wstring LoadStringFromResource(

    __in UINT stringID,

    __in_opt HINSTANCE instance = NULL )


    WCHAR * pBuf = NULL;


    int len = LoadStringW(



        reinterpret_cast< LPWSTR >( &pBuf ),

        0 );


    if( len )

        return std::wstring( pBuf, len );


        return std::wstring();



The above code can be used like this:

       wstring str = LoadStringFromResource( IDS_SOMETHING );


In 2010, I believe we can forget about ANSI strings (which depend on code pages, etc.) and just assume that strings are stored using Unicode (BTW: this is what modern languages like Java, Python, C#, etc. do). So I just wrote a function to load Unicode strings (i.e. wstring) from resources. Moreover, in the aforementioned LoadString MSDN documentation, there is a comment specifying that the special behaviour of nBufferMax == 0 applies only to the Unicode version of LoadString (i.e. LoadStringW).

EDIT 2011/01/08: String construction code updated accordingly to Bo Persson’s suggestion.

2 thoughts on “STL strings: loading from resources”

  1. The std::string has a constructor taking start pointer and length, instead of two iterators. A micro optimization that might be useful.

    if( len )
    return std::wstring( pBuf, len );
    return std::wstring();

Leave a Reply

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