Differences between four types of cast characters for C + +

Source: Internet
Author: User

dynamic_cast as one of the four internal type conversion operators is significantly different from the traditional C-style forced type conversions. In addition to dynamic_cast conversions, the behavior is determined at compile time, whether the conversion succeeds, and does not depend on the object being converted. and dynamic_cast is not. In this case, no more three conversions and C-style conversions are discussed. First, dynamic_cast relies on rtti information, and secondly, at the time of conversion, dynamic_cast checks whether the converted source object can actually be converted to the target type, which is not syntactically, but a real-world check. First look at the relevant parts of Rtti, usually, many compilers find the object's Rtti information through vtable, which means that if the base class does not have a virtual method, it will not be able to determine the real type of the object that a base class pointer variable refers to, at this time, dynamic_cast can only be used to do a safe conversion, For example, a pointer from a derived class is converted to a base class pointer. This conversion does not need to be dynamic_cast involved. In other words, dynamic_cast is based on the information Rtti recorded to determine whether the type conversion is legitimate. Here's an example:structb1{Virtual~B1 () {}};structb2{Virtual~B2 () {}};structd1:b1, b2{};intMain () {D1 D; B1* PB1 = &D; B2* PB2 = dynamic_cast<b2*> (PB1);//L1b2* pb22 = static_cast<b2*> (PB1);//L2    return 0;} As you can see in the above definition, B1 and B2 are unrelated classes, and from L1 you can see that dynamic_cast allows for this conversion: As long as the B1 has a polymorphic method. L2 fails the compilation, static_cast does not allow two completely unrelated classes to convert from one to the other. Dynamic_ This property of cast is very useful when extracting an interface of an object, which is similar to the QueryInterface function of COM. Right on the Internet to see an article on Forced transformation: http://www.xker.com/article/articleview/2005-8-23/article_view_2732.htmThis is described in this article:--dynamic_cast is primarily used to perform "safe downcasting", that is, to determine whether an object is a specific type in an inheritance system. ---This description is incomplete, dynamic_cast can achieve a complete downward transformation, but also to achieve a more powerful QueryInterface function. ************************************************************on the issue of coercion type conversion, many books have been discussed, the most detailed written is CC + + 's "Design and Evolution" by the father of + +. The best solution is not to use the C-style coercion type conversion, but instead use the standard C + + type conversion character: Static_cast, dynamic_cast. Standard C + +There are four types of conversion characters: static_cast, dynamic_cast, reinterpret_cast, and const_cast. Each of them is described below. Static_cast Usage: static_cast< Type-id >(expression) The operator converts expression to type-The ID type, but there is no run-time type check to guarantee the security of the conversion. It is mainly used for conversions between basic data types, such as converting int to char, and converting int to enum. The security of this conversion is also to be ensured by the developer. Converts a null pointer to a null pointer of the target type. Converts any type of expression to a void type. Note: static_cast cannot convert the const, Volitale, or __unaligned properties of expression. dynamic_cast Usage: dynamic_cast< Type-id >(expression) The operator converts expression to typeAn object of type-id. Type-id must be a pointer to a class, a reference to a class, or void *; if Type-id is a class pointer type, expression must also be a pointer if type-ID is a reference, then expression must also be a reference. The dynamic_cast is primarily used for upstream and downstream conversions between class hierarchies, and can also be used for cross-conversion between classes. The effect of dynamic_cast and static_cast is the same when upstream conversions are made between class hierarchies, and dynamic_cast has the function of type checking, which is more secure than static_cast when making a downstream conversion. classb{ Public:intM_inum;Virtual voidfoo ();};classD: Publicb{ Public:Char*m_szname[ -];};voidFunc (B *pb) {D*PD1 = Static_cast<d *>(pb);D*PD2 = Dynamic_cast<d *>(PB);} In the preceding code snippet, if PB points to an object of type D, PD1 and PD2 are the same, and any operation that performs type D on both pointers is safe, but if PB points to an object of type B, then PD1 will be a pointer to that object. It would be unsafe to do a type D operation (such as access to M_szname), and PD2 would be a null pointer. Also note: B to have virtual function, or compile error, static_cast There is no such limit. This is because runtime type checking requires run-time type information, and this information is stored in the virtual function table of the class (the concept of virtual function tables is detailed and visible<inside C + +ObjectModel>, only the classes that define the virtual function have a virtual function table, and the class without the virtual function is not a virtual function table. In addition, the dynamic_cast supports cross-cast. As shown in the following code. classa{ Public:intM_inum;Virtual voidf () {}};classB: Publica{};classD: Publica{};voidfoo () {B*PB =NewB;PB->m_inum = -;D*PD1 = Static_cast<d *> (pb);//copile ErrorD*PD2 = Dynamic_cast<d *> (pb);//PD2 is NULLdelete PB;} In function foo, a conversion using static_cast is not allowed and will fail at compile time, whereas a conversion using dynamic_cast is allowed with the result of a null pointer. Reinpreter_cast Usage: reinpreter_cast<type-id>(expression) type-The ID must be a pointer, reference, arithmetic type, function pointer, or member pointer. It can convert a pointer to an integer, or an integer to a pointer (a pointer is converted to an integer, the integer is converted to the original type of pointer, and the original pointer value can be obtained). The operator uses more. Const_cast Usage: const_cast<type_id>(expression) This operator is used to modify the const or volatile properties of a type. In addition to const or volatile adornments, the type_id and expression types are the same. The constant pointer is converted to a very pointer, and still points to the original object, the constant reference is converted to a very literal reference and still points to the original object, and the constant object is converted to a very mass object. Voiatile and const class test. As an example:classb{ Public:intM_inum;}voidfoo () {ConstB B1;b1.m_inum= -;//comile ErrorB B2= const_cast<b>(B1); B2. M_inum= $;//FineThe above code compiles with an error, because B1 is a constant object and cannot be changed, and using const_cast to convert it to a constant object, it can arbitrarily change its data members. Note: B1 and B2 are two different objects.
Reprinted from: http://blog.csdn.net/acdnjjjdjkdckjj/article/details/5976564

Differences between four types of cast characters for C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.