

In fact, for the previous conversion, std::wstring needs to know the exact length of the input string (i.e. a “raw C-style NUL-terminated wchar_t-based read-only string pointer”, so there’s a perfect match here! On the other side, std::wstring has an overloaded constructor expecting exactly a “const wchar_t*”, i.e. a “raw C-style NUL-terminated wchar_t-based read-only string pointer”.

So, CString is happy to be automatically converted to a “const wchar_t*”, i.e. The last line converting from CString to std::wstring works since CString has an implicit conversion operator to LPCTSTR, which in Unicode builds is equivalent to “const wchar_t*”.

and pass a CString instance that will be filled Just follow the method's prototype literally, In code: // void DoSomething(CString& outputString) Here, what I suggest is to simply create an instance of CString, pass it as the output string parameter, and then just convert the returned CString to a std::wstring. Now, let’s consider the CString& output case. How can a std::wstring instance be passed to a “const wchar_t*” parameter? Simple: just call its c_str() method! // void DoSomething(LPCTSTR inputString) So, in the input case, in Unicode builds, the string is usually represented as a raw C-style NUL-terminated “ const wchar_t*” pointer. In Unicode builds, TCHAR is equivalent to wchar_t. The LPCTSTR typedef is equivalent to “ const TCHAR*“.

(“ANSI” builds are something of the past, and to me they don’t make much sense in modern C++ Windows software they are also a big source of trouble and confusion between “ANSI” code page, several other different code pages, etc.). For example, ATL, WTL and MFC’s classes use the CString class as their “native” string type.īefore moving forward, let me clarify that I’m going to discuss the case of Unicode builds, which have been the default since probably Visual Studio 2005. I wrote a detailed article published on MSDN Magazine on “Using STL Strings at Win32 API Boundaries”, which may be interesting or helpful for someone.īut here I’d like to discuss a specific slightly different scenario, that is the “interoperability” of STL’s strings with ATL or MFC-based code.Ī common pattern in this context is having CString used as the default string class, instead of STL’s strings. Many C++ beginners (and not only beginners…) seem to struggle when dealing with STL’s strings in Win32 C++ code.
