另一个问题的答案:Strict aliasing rule and 'char *' pointers说使用 char*
检查 T
对象的二进制内容是可以的。但是使用 T*
覆盖在字符缓冲区上是不行的。
现在我有一个函数,它接受一个带有二进制数据的字符缓冲区。并在阅读时做这样的事情:
// unsigned char *pData used to walk through the buffer.
uint32_t value = *(unit32_t*)pData;
pData += 4;
如果我这样做打破了严格的别名,还有什么其他更有效的方法可用?当使用少量字节调用 memcpy 时,编译器会优化它们吗?
最佳答案
If I break the strict aliasing by doing this ...
是的,是的
what other, more effective ways available?
如果缓冲区必须是char
,您需要在访问值之前使用memcpy
到uint32_t
。当然,如果您所有的值都是 uint32_t
,您可以制作一个 uint32_t
缓冲区,并将其传递给用 char
填充它的函数>s,因为严格别名是一种单向禁止,即允许使用 uint32_t*
作为 char*
。
Will compilers optimize memcpy calls when they are called with small amount of bytes?
许多 CPU 都有用于 memcpy
的内置指令。现代编译器使用这些指令来提高效率。
关于c - 如何在不违反严格的别名规则的情况下有效地从 char 缓冲区复制小数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986024/