C++ 获取 u8 字符串文字值表示的可移植方法

标签 c++ utf-8 type-conversion c++14

让我们考虑一下:

char const str[] = u8"ñ";
auto const* u8_code_units = reinterpret_cast<unsigned char*>(str); 
// using u8_code_units elements

这是否完全可移植且符合 C++ 标准?或者有一些条款说它是未定义的行为或取决于任何未指定的值?我知道 unsigned charchar应具有相同的对齐要求和 reinterpret_cast<T*>(v)在这种情况下等于 static_cast<T*>(static_cast<void*>(v)) ,所以,我认为使用它是完全安全和便携的,但我不确定。

最佳答案

Is that fully portable and C++ standard compliant?

有点,但不是你想的那样。

看,您必须将该文件以某种格式实际保存到磁盘。这意味着您的编译器必须能够读取相同的格式。编译器支持的文本格式是实现定义的。

但是,如果您的编译器支持您保存它的格式,并且该格式可以保存 Unicode 编码的字符,那么您的编译器将在这里做正确的事情。

即使是 reinterpret_cast 也没问题,因为编译器要求 char 数组可以通过 unsigned char 数组访问,即使平台的 char 已签名。该标准明确要求,当通过 unsigned char 读取 UTF-8 格式的 char 数组时,您将获得您期望从 UTF-8 格式获得的位。

但是请注意:

I know that unsigned char and char shall have the same alignment requirements and reinterpret_cast(v) equals in that case to static_cast(static_cast(v)),

那不足以保护你。它起作用是因为标准明确说它在这种特殊情况下起作用,而不是因为对齐要求等。 charunsigned char 有异常(exception)的别名规则允许这样做;对齐与它无关。

关于C++ 获取 u8 字符串文字值表示的可移植方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45993006/

相关文章:

casting - 如何检查整数值是否已保存在 float 中?

android - 将带时间的字符串转换为分钟

c++ - _bstr_t 到 UTF-8 可能吗?

python - 在 Python 中打开文件读取时应该使用 utf8 还是 utf-8-sig?

arrays - 使用字素与分割的 UTF-8 字符串数组

java - 如何在字符串中插入≠符号

c# - 在 LINQ 中将 datetime2 转换为字符串 ("dd/MM/yyyy")

c++ - 使用 std::move,调用 move 构造函数但对象仍然有效

c# - 从 const char* 复制到字节数组 C++/c# interop Marshal::Copy

c++ - kAudioDevicePropertyNominalSampleRate 的 AudioObjectAddPropertyListener