我听说static_cast函数应该优于c风格或简单函数风格的强制转换。这是真的吗?为什么?
当前回答
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除了操作指向类的指针外,还可以用于执行类中显式定义的转换,以及执行基本类型之间的标准转换:
double d = 3.14159265;
int i = static_cast<int>(d);
一个实用的提示:如果您计划整理项目,可以在源代码中轻松搜索static_cast关键字。
Static_cast意味着您不能意外地使用const_cast或reinterpret_cast,这是一件好事。
In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() can be spotted easily anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot. Intentions are conveyed much better using C++ casts. More Explanation: The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char. char c = 10; // 1 byte int *p = (int*)&c; // 4 bytes Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory. *p = 5; // run-time error: stack corruption In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation. int *q = static_cast<int*>(&c); // compile-time error
阅读更多: static_cast<>和C风格强制转换有什么区别 而且 常规强制转换与静态强制转换与动态强制转换
这与您希望施加的类型安全性有关。
当你写(bar) foo(如果你没有提供类型转换操作符,这相当于reinterpret_cast<bar> foo)时,你是在告诉编译器忽略类型安全,只做它被告知的事情。
当您编写static_cast<bar> foo时,您是在要求编译器至少检查类型转换是否有意义,并且对于整型类型,要插入一些转换代码。
编辑2014-02-26
这个答案是我5年前写的,但我错了。(见注释)。但它仍然得到了赞!