应该在新写的C++(www.cppentry.com) 代码中杜绝旧式强制类型转换,因为用文本查找工具在代码中无法完全找出这种转换。某些编译器可以对旧式转换给出警告,例如g++的-Wold-style-cast 选项。
Prior to the introduction of named cast operators, an explicit cast was performed by enclosing a type in parentheses:
- char *pc = (char*) ip;
The effect of this cast is the same as using the reinterpret_cast notation. However, the visibility of this cast is considerably less, making it even more difficult to track down the rogue cast.
Standard C++(www.cppentry.com) introduced the named cast operators to make casts more visible and to give the programmer a more finely tuned tool to use when casts are necessary. For example, nonpointer static_casts and const_casts tend to be safer than reinterpret_casts. As a result, the programmer (as well as readers and tools operating on the program) can clearly identify the potential risk level of each explicit cast in code.
Although the old-style cast notation is supported by Standard C++(www.cppentry.com), we recommend it be used only when writing code to be compiled either under the C language or pre-Standard C++(www.cppentry.com).
旧式转型有两种写法,第一种看起来像函数调用,但“函数名”是个类型名;第二种是从C 语言里继承的写法。第一种写法其实是对象构造的语法,Type(val)构造一个Type 类型的匿名对象,以val 为其直接初始化(direct-initialization)的实参。C++(www.cppentry.com) 支持第一种写法,是为了在语法上兼容内置类型与class 类型,这在编写模板代码的时候有用。
The old-style cast notation takes one of the following two forms:
- type (expr);
- (type) expr;
Depending on the types involved, an old-style cast has the same behavior as a const_cast, a static_cast, or a reinterpret_cast. When used where a static_cast or a const_cast would be legal, an old-style cast does the same conversion as the respective named cast. If neither is legal, then an old-style cast performs a reinterpret_cast. For example, we might rewrite the casts from the previous section less clearly using old-style notation:
- int ival; double dval;
- ival += int (dval);
- const char* pc_str;
- string_copy((char*)pc_str);
- int *ip;
- char *pc = (char*)ip;
The old-style cast notation remains supported for backward compatibility with programs written under pre-Standard C++(www.cppentry.com) and to maintain compatibility with the C language.
EXERCISES SECTION 5.12.7
Exercise 5.32: Given the following set of definitions,
- char cval; int ival; unsigned int ui;
- float fval; double dval;
identify the implicit type conversions, if any, taking place:
(a) cval = ’a’ + 3; (b) fval = ui - ival * 1.0;
(c) dval = ui * fval; (d) cval = ival + fval + dval;
Exercise 5.33: Given the following set of definitions,
- int ival; double dval;
- const string *ps; char *pc; void *pv;
rewrite each of the following using a named cast notation:
(a) pv = (void*)ps; (b) ival = int(*pc);
(c) pv = &dval; (d) pc = (char*) pv;