gpt4 book ai didi

c++ - wchar_t 和 char16_t 在 Windows 上是一样的吗?

转载 作者:可可西里 更新时间:2023-11-01 09:44:13 25 4
gpt4 key购买 nike

我有一个 std::u16string 的实例,我可以将它的 c_str() 传递给需要 LPCWSTR 的 Win32 API,而无需任何类型的转换?例如,我可以安全地这样做吗:

auto u16s = std::u16string(u"Hello");
::SetWindowTextW(hWnd, reinterpret_cast<LPCWSTR>(u16s.c_str()));

已更新,MSDN 说 here wchar_t 是 UTF-16LE,而 char16_t 只是没有指定字节序的 UTF-16。那么可以安全地假设 char16_t 在 Windows 上也始终是 UTF-16LE 吗?或者那是特定于 MSVC 编译器的,因此如果我使用 GCC 编译,它可能是 UTF-32LE(或者可能是 UTF-16BE)?

最佳答案

我想弥补@jamesdlin 的anwser尽管他的回答是正确的。

在C++11之前,有charwchar_t , 因此专门研究 std::basic_string<>std::stringstd::wstring .

但是,wchar_t 的宽度(以位为单位)特定于平台:在 Windows 上它是 16 位,而在其他平台上是 32 位。

随着 C++11 的出现,标准 adds char16_t表示 16 位宽的字符;因此在 Windows 上,std::u16string恰好可以与 std::wstring 互换在大多数情况下,因为它们都能够表示 16 位宽的字符。

The wchar_t type is an implementation-defined wide character type. In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.

但是最新的MSDN好像加了一些aside notes对于使用 std::wstring 的代码但打算便携:

The size of wchar_t is implementation-defined. If your code depends on wchar_t to be a certain size, check your platform's implementation (for example, with sizeof(wchar_t)). If you need a string character type with a width that is guaranteed to remain the same on all platforms, use string, u16string, or u32string.

至于LE(little-endian),它应该是架构特定的,IIRC。当今大多数架构都使用 LE。

关于c++ - wchar_t 和 char16_t 在 Windows 上是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com