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

问题描述

我想将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)错了?同时,我可以这样做吗?

标签: c++

解决方案


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

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

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

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


推荐阅读