使用 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?
我想将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
有两个字节)。
相关文章:
- C++通常的算术转换不转换
- 将图像魔术转换命令转换为魔术++c++代码
- 检查是否需要 utf8 转换并转换为 utf8
- 静态强制转换允许转换对象指针,但不允许转换整数
- 管理到本机值类转换:强制转换指针是否安全?
- 使用递归前缀转换前缀转换
- FFMpeg与OpenCV的格式转换/简单转换
- 转换操作员 转换构造函数=不直觉的行为
- c++多态性:基类的上转换/下转换和容器,缺少数据
- 如何将转换函数转换为lambda表达式
- 将指针 (T*) 强制转换或转换为两个常量 (T 常量 * 常量) 指针
- 如何在模板中的类型之间进行转换并转换回原始类型
- 比较双精度和整数,不进行转换或转换
- 如何将 CString 转换或转换为 LPWSTR
- 将新C++转换为旧C++
- 无法转换参数-转换丢失限定符
- 词法转换部分转换-有可能吗
- 如何转换tf::转换为btTransform
- 可接受的编程实践.转换和转换
- 两个指针之间的转换/强制转换