Should I use a C++ reinterpret_cast over a C-style cast?(我应该在 C 样式转换上使用 C++ 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 风格(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++-casts,从长远来看会让生活更轻松.在这种情况下,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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该在 C 样式转换上使用 C++ reinterpret_cast 吗?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
