Visual C++: Migrating traditional C and C++ string code to a Unicode world

前端 未结 6 1881
半阙折子戏
半阙折子戏 2021-02-05 15:37

I see that Visual Studio 2008 and later now start off a new solution with the Character Set set to Unicode. My old C++ code deals with only English ASCII text and is full of:

6条回答
  •  广开言路
    2021-02-05 16:32

    I would suggest not to worry about supporting both ascii and unicode build (a-la TCHAR) and go stright to unicode. That way you get to use more of the platform independant functions (wcscpy, wcsstr etc) instead of relying onto TCHAR functions which are Micrpsoft specific.

    You can use std::wstring instead of std::string and replace all chars with wchar_ts. With a massive change like this I found that you start with one thing and let the compiler guide you to the next.

    One thing that I can think of that might not be obvious at run time is where a string is allocated with malloc without using sizeof operator for the underlying type. So watch out for things like char * p = (char*)malloc(11) - 10 characters plus terminating NULL, this string will be half the size it's supposed to be in wchar_ts. It should become wchar_t * p = (wchar_t*)malloc(11*sizeof(wchar_t)).

    Oh and the whole TCHAR is to support compile time ASCII/Unicode strings. It's defined something like this:

    #ifdef _UNICODE
    #define _T(x) L ## x
    #else
    #define _T(x) ## x
    #endif
    

    So that in unicode configuration _T("blah") becomes L"blah" and in ascii configuration it's "blah".

提交回复
热议问题