Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would std::basic_string<TCHAR> be preferable to std::wstring on Windows?

As I understand it, Windows #defines TCHAR as the correct character type for your application based on the build - so it is wchar_t in UNICODE builds and char otherwise.

Because of this I wondered if std::basic_string<TCHAR> would be preferable to std::wstring, since the first would theoretically match the character type of the application, whereas the second would always be wide.

So my question is essentially: Would std::basic_string<TCHAR> be preferable to std::wstring on Windows? And, would there be any caveats (i.e. unexpected behavior or side effects) to using std::basic_string<TCHAR>? Or, should I just use std::wstring on Windows and forget about it?

like image 255
Matt Ryan Avatar asked Jun 05 '09 15:06

Matt Ryan


3 Answers

I believe the time when it was advisable to release non-unicode versions of your application (to support Win95, or to save a KB or two) is long past: nowadays the underlying Windows system you'll support are going to be unicode-based (so using char-based system interfaces will actually complicate the code by interposing a shim layer from the library) and it's doubtful whether you'd save any space at all. Go std::wstring, young man!-)

like image 146
Alex Martelli Avatar answered Oct 18 '22 03:10

Alex Martelli


I have done this on very large projects and it works great:

namespace std
{
#ifdef _UNICODE
    typedef wstring tstring;
#else
    typedef string tstring;
#endif
}

You can use wstring everywhere instead though if you'd like, if you do not need to ever compile using a multi-byte character string. I don't think you need to ever support multi byte character strings though in any modern application.

Note: The std namespace is supposed to be off limits, but I have not had any problems with the above method for several years.

like image 9
Brian R. Bondy Avatar answered Oct 18 '22 03:10

Brian R. Bondy


One thing to keep in mind. If you decide to use std::wstring all the way in your program, you might still need to use std::string if you are communicating with other systems using UTF8.

like image 3
ralphtheninja Avatar answered Oct 18 '22 02:10

ralphtheninja