我听说static_cast函数应该优于c风格或简单函数风格的强制转换。这是真的吗?为什么?
当前回答
Static_cast意味着您不能意外地使用const_cast或reinterpret_cast,这是一件好事。
其他回答
Static_cast除了操作指向类的指针外,还可以用于执行类中显式定义的转换,以及执行基本类型之间的标准转换:
double d = 3.14159265;
int i = static_cast<int>(d);
Static_cast意味着您不能意外地使用const_cast或reinterpret_cast,这是一件好事。
这与您希望施加的类型安全性有关。
当你写(bar) foo(如果你没有提供类型转换操作符,这相当于reinterpret_cast<bar> foo)时,你是在告诉编译器忽略类型安全,只做它被告知的事情。
当您编写static_cast<bar> foo时,您是在要求编译器至少检查类型转换是否有意义,并且对于整型类型,要插入一些转换代码。
编辑2014-02-26
这个答案是我5年前写的,但我错了。(见注释)。但它仍然得到了赞!
一个实用的提示:如果您计划整理项目,可以在源代码中轻松搜索static_cast关键字。
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++介绍