【发布时间】:2013-11-06 00:19:43
【问题描述】:
我正在尝试对地址执行算术运算。我需要确保它位于 4 字节字边界上。这需要我获取指针的无符号整数表示来执行一些数学运算。我已经这样做了:
//memStartAddr is of type void* (from an external API function)
data32 tempAddr = reinterpret_cast<data32>(memStartAddr);
//adjust pointer to the next word boundary if needed
tempAddr = wordAlign(tempAddr);
//memStartAddress is a class variable of type unsigned char*
memStartAddress = reinterpret_cast<data8*>(tempAddr);
//calculate bytes lost due to above adjustment
data32 delta = (tempAddr - reinterpret_cast<data32>(memStartAddress));
//Take advantage of integer arithmetic to ensure usable size is a multiple
//of 4 bytes. Remainders are lost. Shrinks usable size if necessary.
memSize = ((size - delta) / 4) * 4;
这一切都在我的测试中有效,但是,使用 reinterpret_cast 被认为是一种禁止的做法。还有另一种方法可以做到这一点吗?或者是这里有必要的规则例外?
【问题讨论】:
-
我认为这是使用
reinterpret_cast的有效案例 -
谁说
reinterpret_cast是被禁止的?您是否遵循某人的编码约定? -
如果
reinterpret_cast是被禁止的,为什么ISO C++的人认为这是一个好主意并批准将其添加到语言中,为什么每个C++编译器都必须实现它才能符合?在被禁止的事情上浪费了很多生产力,不是吗! -
我同意,但是,这是我在我工作的团队中必须遵循的编码指南中的一条规则,这就是为什么我正在寻求一种可读、直观的解决方法。我相信它必须防止知识渊博的人错误地使用它,因为如果你不小心,你真的会把事情搞砸。
-
@radensb:“将指针对齐到 4 字节边界”会在需要 8 字节的平台上搞砸。
reinterpret_cast的明确意图是这些危险的事情是可能且可见。在 C 中,等价于*(type*)(&expr),这很容易被忽略。