【发布时间】:2013-04-18 03:10:11
【问题描述】:
根据 Effective C++,“将对象地址转换为 char* 指针,然后对它们使用指针算术运算几乎总是会产生未定义的行为。”
对于普通旧数据是否如此?例如,在我很久以前编写的这个模板函数中,用于打印对象的位。它在 x86 上运行得非常好,但是……它是可移植的吗?
#include <iostream>
template< typename TYPE >
void PrintBits( TYPE data ) {
unsigned char *c = reinterpret_cast<unsigned char *>(&data);
std::size_t i = sizeof(data);
std::size_t b;
while ( i>0 ) {
i--;
b=8;
while ( b > 0 ) {
b--;
std::cout << ( ( c[i] & (1<<b) ) ? '1' : '0' );
}
}
std::cout << "\n";
}
int main ( void ) {
unsigned int f = 0xf0f0f0f0;
PrintBits<unsigned int>( f );
return 0;
}
【问题讨论】:
-
我没有花时间完全了解这里的代码,但我知道这可能导致未定义行为(或崩溃)的一个原因是,如果您尝试使用指针算法来处理随机地址为 int,不一定与“字边界”(0、4、8、12、16 等字节)对齐。
-
好的,现在我确实理解了代码,并且正如我所怀疑的那样,这不会是一个问题,因为你不会再转换回 int 了。我不知道这样做是否还有其他问题。
标签: c++ pointers portability