尽管关于 reinterpret_cast 的主题写了很多行,而且它有多糟糕,但我仍然对避免它的最佳方法感到困惑,尤其是在处理从 fstream 读取和写入之类的函数时。所以,这是我的困境......
假设我们有一个整数数组,我们想用文件中的一些数据填充它。
std::ifstream iFile( ... );
// presume that the type of this array is not a matter of choice
int *a = new int[ 100 ];
我们可以用几个不同的演员来阅读:
iFile.read( (char *)a, sizeof( int ) * 100 );
iFile.read( reinterpret_cast< char * >( a ), sizeof( int ) * 100 );
iFile.read( static_cast< char * >( static_cast< void * >( ( a ) ), sizeof( int ) * 100 );
第一个(C 风格)已经过时,我们在 C++ 中引入了新的风格转换,这是有充分理由的。第二个是不可移植的,不提供任何保证。第三个写起来很乏味,破坏了乐趣。
有没有其他选择,我应该怎么做?
编辑:
目标是实现代码尽可能可移植和符合标准。