Lav*_*ven 6 c++ fstream reinterpret-cast
尽管有很多关于 reinterpret_cast 主题的文章,以及它有多糟糕,但我仍然对避免它的最佳方法感到困惑,尤其是在处理诸如从 fstream 读取和写入之类的函数时。所以,这是我的困境......
假设我们有一个整数数组,我们想用文件中的一些数据填充它。
std::ifstream iFile( ... );
// presume that the type of this array is not a matter of choice
int *a = new int[ 100 ];
Run Code Online (Sandbox Code Playgroud)
我们可以阅读一些不同的演员表:
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 );
Run Code Online (Sandbox Code Playgroud)
第一个(C 风格)已经过时,我们在 C++ 中引入了新的风格转换,这是有充分理由的。第二个是不可移植的,不提供任何保证。第三个写起来很乏味,破坏了乐趣。
有什么替代方法吗,我应该怎么做?
编辑:
目标是使代码尽可能可移植且符合标准。
你为什么不声明a为char*,就像这样:
//int *a = new int[100];
char *a = new char[100];
iFile.read(a, 100 );
Run Code Online (Sandbox Code Playgroud)
现在不需要铸造。
编辑:
好的,我阅读了您的评论和您帖子中的评论行。在这种情况下:
iFile.read(reinterpret_cast<char*>(a), sizeof(int)*100);
Run Code Online (Sandbox Code Playgroud)
应该足够了。
但是,我个人会选择 C 风格的演员表:
iFile.read((char*)a, sizeof(int)*100);
Run Code Online (Sandbox Code Playgroud)
那是因为我看不到这里有任何危险。即使使用 C 型演员,一切似乎都很好!
定义这个函数模板:
template<class To, class From>
To any_cast(From v)
{
return static_cast<To>(static_cast<void*>(v));
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
//`From` type will be inferred from the function argument. :-)
iFile.read(any_cast<char*>(a), sizeof(int)*100);
Run Code Online (Sandbox Code Playgroud)
看起来挺好的?
我认为这any_cast可以用于从任何类型转换为任何类型!