Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c++ - Why doesn't STL "officially" support std::string to std::wstring conversions?

I am aware that std::string and std::wstring come from the same base type std::basic_string<>. But there isn't an "official" way to convert std::string data to std::wstring using the C++ STL? I mean Windows provide MultiByteToWideChar() to convert but why cant the STL provide one?

I used std::codecvt before to get it done but now it says that it is deprecated. Why does the STL remove this support the first place?

Thanks in advance.

question from:https://stackoverflow.com/questions/65927281/why-doesnt-stl-officially-support-stdstring-to-stdwstring-conversions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The character encoding of std::string is not defined by the C++ standard, a std::string can hold any encoding that can be represented using 1-byte char elements, which includes UTF-7/8, ISO-8859-x, Windows-125x, etc.

Also, the size of wchar_t is implementation-defined, not defined by the standard, so even the encoding of std::wstring can vary, too. On Windows, wchar_t is 2 bytes, so std::wstring uses UCS-2/UTF-16 encoding. Whereas on other platforms, wchar_t is 4 bytes, so std::wstring uses UCS-4/UTF-32.

So, there is no single conversion that satisfies all possible combinations of std::string <-> std::wstring conversions across all platforms and use-cases. So, you need to know the encoding of the source string, and the intended encoding of the target string, in order to perform a conversion.

And yes, the C++ standard did provide std::codecvt and std::wstring_convert/std::wbuffer_convert for this task, but they have been deprecated, as you have noted. There is no standard replacement provided (yet?).

So, you are best off using 3rd party Unicode API/libraries to handle character conversions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...