使用 char16_t 类型作为 char[] 数组,并通过 reinterpret_cast<> 重新转换它。我的代码是否有未定义的行为?

Use char16_t type as an array of char[] and reconvert it via reinterpret_cast<>. Does my code have undefined behavior?

本文关键字:转换 新转换 代码 未定义 是否 我的 lt char 类型 char16 数组      更新时间:2023-10-16

我想将char16_t类型的对象内存表示形式检查为char[]数组,并通过reinterpret_cast<>重新转换它。我的代码是否有未定义的行为?

我的转换代码如下:

char16_t code;
..... // some operating ensure the variable 'code' keep a value
for (auto rbegin = reinterpret_cast<char*>(&code + 1), rend = reinterpret_cast<char*>(&code); rbegin != rend;)
    fout.put(*(--rbegin));

我的主要问题是reintepret_cast<char*>(&code +1)错了吗?同时,我可以这样做吗?

code 不是

char16_t 的数组(尽管它可以被视为 1 个元素的数组)。因此,取消引用&code + 1将导致在您越界访问时出现未定义的行为。

相反,您可以执行以下操作,这是安全的:

rbegin = reinterpret_cast<char*>(&code) + 1

由于reinterpret_cast<char*>(&code)将导致指向 char 的指针,因此将 1 加 表示您仍在允许访问的内存限制内。(我在这里假设char16_t有两个字节)。