任何reinterpret_cast更改指针值的真实示例? [英] Any real example of reinterpret_cast changing a pointer value?

查看:187
本文介绍了任何reinterpret_cast更改指针值的真实示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++标准, reinterpret_cast 的指针 T * 到其他类型的指针 Q * 可以更改或不更改指针值取决于实现。



我很感兴趣 - 它有一个C ++实现的实例,其中转换一个指针到其他指针类型与 reinterpret_cast 更改指针?

解决方案

请注意,当标准声明它可以或不可能做某事时,意味着有任何当前的实现具有这种行为,只有他们可以。



我可以想到的最接近的是一个架构,其中类型对齐是硬件需要的,以及如果需要,决定校正对齐的实现。像:

  aligned8 var; 
aligned1 * p = reinterpret_cast< aligned1 *>(& var);
aligned1 * q = p + 1; //假设对齐的1大小不是8的倍数
aligned8 * a = reinterpret_cast< aligned8 *>(q); // [1]

可能需要 code>是一个有效的指针,它必须寻址8的内存位置倍数,而具有较少对齐要求的参数 q 可以指向任何内存地址。 / p>

According to C++ Standard, a reinterpret_cast of a pointer T* to some other type pointer Q* can change or not change the pointer value depending on implementation.

I'm very interested - it there any real example of a C++ implementation where casting a pointer to some other pointer type with reinterpret_cast changes the pointer? What and why is changed there?

解决方案

Note that when the standard states that it can or cannot possibly do something, it does not mean that there is any current implementation that has that behavior, only that they could.

The closest that I can think of is an architecture where type alignment was required by the hardware, and an implementation that decided to correct alignment if needed. Something like:

aligned8 var;
aligned1 *p = reinterpret_cast<aligned1*>(&var);
aligned1 *q = p + 1; // assuming aligned 1 size is not multiple of 8
aligned8 *a = reinterpret_cast<aligned8*>(q); // [1]

There could be a requirement that for a to be a valid pointer it has to address a memory position multiple of 8, while the argument q with lesser alignment requirements could point to any memory address.

这篇关于任何reinterpret_cast更改指针值的真实示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆