gpt4 book ai didi

GCC 和 MSVC 中的 C++ utf-8 文字

转载 作者:行者123 更新时间:2023-12-01 13:05:40 28 4
gpt4 key购买 nike

这里我有一些简单的代码:

#include <iostream>
#include <cstdint>

int main()
{
const unsigned char utf8_string[] = u8"\xA0";
std::cout << std::hex << "Size: " << sizeof(utf8_string) << std::endl;
for (int i=0; i < sizeof(utf8_string); i++) {
std::cout << std::hex << (uint16_t)utf8_string[i] << std::endl;
}
}
我在这里看到 MSVC 和 GCC 的不同行为。
MSVC 见 "\xA0"作为未编码的 unicode 序列,并将其编码为 utf-8。
所以在 MSVC 中,输出是:

C2A0


在 utf8 unicode 符号中正确编码 U+00A0 .
但是在 GCC 的情况下,什么也没有发生。它将字符串视为简单的字节。即使我删除 u8 也没有变化在字符串文字之前。
两个编译器都编码为 utf8,输出 C2A0如果字符串设置为: u8"\u00A0";为什么编译器的行为不同,哪个实际上是正确的?
用于测试的软件:

GCC 8.3.0

MSVC 19.00.23506


C++ 11

最佳答案

他们都错了。

据我所知,C++17 标准说 here那:

The size of a narrow string literal is the total number of escape sequences and other characters, plus at least one for the multibyte encoding of each universal-character-name, plus one for the terminating '\0'.



尽管还有其他提示,但这似乎是转义序列不是多字节并且 MSVC 的行为错误的最有力的迹象。

有针对此的票证,目前标记为“正在调查”:
  • https://developercommunity.visualstudio.com/content/problem/225847/hex-escape-codes-in-a-utf8-literal-are-treated-in.html
  • https://developercommunity.visualstudio.com/content/problem/260684/escape-sequences-in-unicode-string-literals-are-ov.html

  • 但是它也说 here关于 UTF-8 文字:

    If the value is not representable with a single UTF-8 code unit, the program is ill-formed.



    0xA0不是有效的 UTF-8 字符,程序不应编译。

    注意:
  • u8 开头的 UTF-8 文字被定义为狭窄。
  • \xA0是一个转义序列
  • \u00A0被视为通用字符名称而不是转义序列
  • 关于GCC 和 MSVC 中的 C++ utf-8 文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61505874/

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