c++ - Windows 上代理项对(BMP 之外的 Unicode 字符)的 wchar_t* 大小

标签 c++ windows unicode utf-16

我在 Windows 8 上遇到了一个有趣的问题。我测试过我可以用 wchar_t* 字符串表示 BMP 之外的 Unicode 字符。以下测试代码对我产生了意想不到的结果:

const wchar_t* s1 = L"a";
const wchar_t* s2 = L"\U0002008A"; // The "Han" character

int i1 = sizeof(wchar_t); // i1 == 2, the size of wchar_t on Windows.

int i2 = sizeof(s1); // i2 == 4, because of the terminating '\0' (I guess).
int i3 = sizeof(s2); // i3 == 4, why?

U+2008A 是 Han character ,它不在二进制多语言 Pane 中,因此它应该由 UTF-16 中的代理对表示。这意味着 - 如果我理解正确的话 - 它应该由两个 wchar_t 字符表示。所以我预计 sizeof(s2) 为 6(代理对的两个 wchar_t-s 为 4,终止\0 为 2)。

那么为什么 sizeof(s2) == 4?我测试了 s2 字符串构造正确,因为我用 DirectWrite 渲染了它,并且汉字显示正确。

更新:正如 Naveen 所指出的,我试图错误地确定数组的大小。以下代码产生正确的结果:

const wchar_t* s1 = L"a";
const wchar_t* s2 = L"\U0002008A"; // The "Han" character

int i1 = sizeof(wchar_t); // i1 == 2, the size of wchar_t on Windows.

std::wstring str1 (s1);
std::wstring str2 (s2);

int i2 = str1.size(); // i2 == 1.
int i3 = str2.size(); // i3 == 2, because two wchar_t characters needed for the surrogate pair.

最佳答案

sizeof(s2) 返回存储指针 s2 或任何其他指针所需的字节数,在您的系统上为 4 字节。它与s2指向的存储在中的字符无关。

关于c++ - Windows 上代理项对(BMP 之外的 Unicode 字符)的 wchar_t* 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11503931/

相关文章:

java - 特殊信件翻译成英文

c++ - 尝试实现观察者模式时出现多个编译器错误

c++ - 无法识别的命令行选项 '-stdlib=libc++' gcc (Homebrew gcc 5.3.0) 5.3.0

c++ - 您通常在哪里安装从源代码构建的库的调试版本?

c++ - 如何为游戏 LAN 聚会创建远程查看器?

windows - 插入 USB 驱动器时启动 PowerShell 脚本

c# - 由于缓存,Sqlite 第一次查询在 Windows XP 中花费的时间太长?

Android 将 unicode 字符串设置为 textview

Python unicode string literals::'\u0391' 和 u'\u0391' 有什么区别

c++ - Range-v3 中 Readable 使用的 CommonReference 有什么作用?