c风格的cast vs reinterpret_cast [英] c-style cast vs reinterpret_cast

查看:211
本文介绍了c风格的cast vs reinterpret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模板函数用于将任何标准类型的数据转储到二进制输出流中。

I have the following template function used to dump data of any standard type into a binary output stream.

template<typename T> static void
dump ( const T& v, ostream& o ) {
    o.write ( reinterpret_cast<const char*>(&v), sizeof(T));
}

而不是reinterpret_cast,我也可以使用C风格)。有什么特别的理由使用reinterpret_cast?我读了一些其他的帖子reinterpret_cast被皱眉了。

Instead of the reinterpret_cast I could also use a C-style (const char*). Is there any particular reason to use reinterpret_cast ? I read a few other posts where reinterpret_cast was frowned upon. But the above usage is legal and cannot be replaced with anything else, right ?

感谢

推荐答案

C风格的演员的问题是他们在底下做了很多。详情请参阅这里: http://anteru.net/2007/12/18/200/

The problem with C-Style casts is that they do a lot under the hood. See here for a detailed explanation: http://anteru.net/2007/12/18/200/

您应该尝试始终使用C ++ - casts,从长远来看,使生活更轻松。在这种情况下,C风格的主要问题是你可以写(char *)(& v),而 reinterpret_cast ,你需要一个额外的 const_cast ,所以它有点更安全。此外,您可以使用regex轻松找到 reinterpret_cast ,这对于C风格的转换是不可能的。

You should try to always use the C++-casts, makes life easier in the long run. The main problem with C-style casts in this case is that you could have written (char*)(&v) while with reinterpret_cast, you would need an additional const_cast, so it's a bit safer. Plus you can easily find reinterpret_cast with a regex, which is not possible for the C-style casts.

这篇关于c风格的cast vs reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆