我听说static_cast函数应该优于c风格或简单函数风格的强制转换。这是真的吗?为什么?
当前回答
这与您希望施加的类型安全性有关。
当你写(bar) foo(如果你没有提供类型转换操作符,这相当于reinterpret_cast<bar> foo)时,你是在告诉编译器忽略类型安全,只做它被告知的事情。
当您编写static_cast<bar> foo时,您是在要求编译器至少检查类型转换是否有意义,并且对于整型类型,要插入一些转换代码。
编辑2014-02-26
这个答案是我5年前写的,但我错了。(见注释)。但它仍然得到了赞!
其他回答
一个实用的提示:如果您计划整理项目,可以在源代码中轻松搜索static_cast关键字。
这与您希望施加的类型安全性有关。
当你写(bar) foo(如果你没有提供类型转换操作符,这相当于reinterpret_cast<bar> foo)时,你是在告诉编译器忽略类型安全,只做它被告知的事情。
当您编写static_cast<bar> foo时,您是在要求编译器至少检查类型转换是否有意义,并且对于整型类型,要插入一些转换代码。
编辑2014-02-26
这个答案是我5年前写的,但我错了。(见注释)。但它仍然得到了赞!
Allows casts to be found easily in your code using grep or similar tools. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.
参见有效c++介绍
Static_cast意味着您不能意外地使用const_cast或reinterpret_cast,这是一件好事。
C样式强制转换在代码块中很容易被忽略。c++风格的类型转换不仅是更好的实践;它们提供了更大程度的灵活性。
Reinterpret_cast允许整型到指针类型的转换,但是如果使用不当可能是不安全的。
Static_cast为数值类型提供了良好的转换,例如从enum到int或从int到float或任何您确定类型的数据类型。它不执行任何运行时检查。
另一方面,Dynamic_cast将执行这些检查,标记任何不明确的赋值或转换。它只对指针和引用起作用,会产生开销。
还有一些其他的,但这些是你会遇到的主要的。
推荐文章
- Uint8_t不能用cout打印
- c++中不必要的花括号
- 如何反转一个c++向量?
- 如何开始开发Internet Explorer扩展?
- Std::auto_ptr改为Std::unique_ptr
- int的最大值
- c++中有最大数组长度限制吗?
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 如何在Go中使用c++
- 自定义c++分配器的引人注目的例子?
- RAII和c++中的智能指针
- 如何构建和使用谷歌TensorFlow c++ api
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"