CString or std::string – that is the question

…with apologies to Shakespeare [:)]

So, should we use CString or std::string class to store and manage strings in our C++ code?

Well, if there is a need of writing portable C++ code, the choice should be std::string, which is part of the C++ standard library.

But, in the context of C++ Win32 programming (using ATL or MFC), I find CString class much more convenient than std::string.

These are some reasons:

1) CString allows loading strings from resources, which is good also for internationalization.

2) CString offers a convenient FormatMessage method (which is good for internationalization, too; see for example the interesting problem of “Yoda speak” discussed in this post on Mihai Nita’s blog).

3) CString integrates well with Windows APIs (the implicit LPCTSTR operator comes in handy when passing instances of CString to Windows APIs, like e.g. SetWindowText).

4) CString is reference counted, so moving instances of CString around is cheap.

5) CString offers convenient methods to e.g. tokenize strings, to trim them, etc.

 

Note:
In Visual C++ 6’s timeframe, CString class was part of MFC. But since Visual Studio .NET 2003, CString was factored out of MFC, and was made part of ATL. So, post VC6, it is possible to use CString also in non-MFC code. To use CString in non-MFC code, just #include <atlstr.h> (a good place for that would be “StdAfx.h” precompiled header).

 

Leave a Reply

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


*