c++ - 使用 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)
错了?同时,我可以这样做吗?
解决方案
code
不是char16_t
s 的数组(尽管它可以被视为 1 个元素的数组)。因此,当您越界访问时,取消引用&code + 1
将导致未定义的行为。
相反,您可以执行以下安全操作:
rbegin = reinterpret_cast<char*>(&code) + 1
由于reinterpret_cast<char*>(&code)
将导致指向 的指针char
,因此向其添加 1 意味着您仍在允许访问的内存限制范围内。(我假设这里char16_t
有两个字节)。
推荐阅读
- javascript - 如何在 react.js 中将对象传递给 Formik 表单
- r - 带有虚拟变量的 GARCH 建模
- python - 如何创建创建和打印正方形列表的代码?
- docusignapi - DocuSign - 通过 API 在创建的信封上更改模板定义的收件人
- c++ - 寻址数组中的特定元素时,循环中出现错误“表达式必须具有指向对象的指针类型,但它具有 int 类型”
- java - 在 dropwizard 中的单独线程上进行作业调度
- sql - Postgres C 函数 - 聚合、可变参数、任意数量的任意类型参数
- python - 如何用列表中的下一个非重复数字替换一维列表中的重复数字
- c# - 将 string[] 数组字段分配给另一个相同类型的数组字段 c#
- python-3.x - 如何在python中为相应的java语法编写同时for循环