我应该在C样式的强制转换上使用C ++ reinterpret_cast吗? [英] Should I use a C++ reinterpret_cast over a C-style 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样式(const char * )。使用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 ++-cast,从长远来看使生活更轻松。在这种情况下,C样式转换的主要问题是您可以编写(char *)(& v)
而使用 reinterpret_cast
,您将需要一个额外的 const_cast
,因此它更安全一些。另外,您还可以轻松找到带有正则表达式的 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样式的强制转换上使用C ++ reinterpret_cast吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!