尽管关于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 ++中引入的新样式演员阵容是有充分理由的。第二个是不可支配的,没有保证。第三个是乏味的,写并破坏了乐趣。

有其他选择吗?我应该如何处理?

编辑:

目的是实现尽可能便携的代码并尽可能符合标准配置。

有帮助吗?

解决方案

你为什么不宣布 a 作为 char* 相反,这样:

//int *a = new int[100]; 
char *a = new char[100];
iFile.read(a, 100 ); 

现在不需要铸造。


编辑:

好的,我阅读了您的评论和您帖子中的评论行。在这种情况下:

iFile.read(reinterpret_cast<char*>(a), sizeof(int)*100);

应该足够了。

但是,我个人会选择C风格的演员:

iFile.read((char*)a, sizeof(int)*100);

那是因为我在这里看不到任何危险。即使使用C风格的演员,一切似乎都很好!


最好又不那么乏味的演员

定义此功能模板:

template<class To, class From>
To any_cast(From v)
{
    return static_cast<To>(static_cast<void*>(v));
}

然后使用它:

//`From` type will be inferred from the function argument. :-) 
iFile.read(any_cast<char*>(a), sizeof(int)*100);

看起来不错?

我认为这 any_cast 可以用来从任何类型到任何类型的铸造!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top