其他分享
首页 > 其他分享> > 我应该在C风格的演员表中使用C reinterpret_cast吗?

我应该在C风格的演员表中使用C reinterpret_cast吗?

作者:互联网

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

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

我也可以使用C风格(const char *)代替reinterpret_cast.有没有特别的理由使用reinterpret_cast?我读了一些其他帖子,其中reinterpret_cast不受欢迎.但上述用法是合法的,不能用其他任何东西替换,对吧?

解决方法:

C-Style演员阵容的问题在于他们在幕后做了很多事情.有关详细说明,请参见此处:http://anteru.net/2007/12/18/200/

您应该尝试始终使用C -cast,从长远来看,让生活更轻松.在这种情况下,C风格的强制转换的主要问题是你可以编写(char *)(& v),而使用reinterpret_cast时,你需要一个额外的const_cast,所以它更安全一些.另外,您可以使用正则表达式轻松找到reinterpret_cast,这对于C风格的演员表是不可能的.

标签:reinterpret-cast,c,casting
来源: https://codeday.me/bug/20190927/1824840.html