Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use dynamic_cast in C++

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use dynamic_cast in C++". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how C++ uses dynamic_cast.

C.146: if you cannot avoid moving in the inheritance hierarchy, use dynamic_cast

Reason (reason)

Dynamic_cast checks at run time.

Example (sample)

Struct B {/ / an interface

Virtual void f ()

Virtual void g ()

Virtual ~ B ()

}

Struct D: B {/ / a wider interface

Void f () override

Virtual void h ()

}

Void user (B* pb)

{

If (D* pd = dynamic_cast (pb)) {

/ /... Use D's interface...

}

Else {

/ /... Make do with B's interface...

}

}

Using other type conversions does not guarantee type safety and causes the program to access a variable that is actually type X as type Z.

Void user2 (B* pb) / / bad

{

D* pd = static_cast (pb); / / I know that pb really points to a D; trust me

/ /... Use D's interface...

}

Void user3 (B* pb) / / unsafe

{

If (some_condition) {

D* pd = static_cast (pb); / / I know that pb really points to a D; trust me

/ /... Use D's interface...

}

Else {

/ /... Make do with B's interface...

}

}

Void f ()

{

B b

User (& b); / / OK

User2 (& b); / / bad error

User3 (& b); / / OK * if* the programmer got the some_condition check right

}

Note (Note)

Like other types of conversions, dynamic_cast is overused. You should use virtual functions rather than type conversions. Static polymorphism should be used when moving in an inheritance system if it is possible (no execution time decision is required) and more convenient.

Note (Note)

Some people using dynamic_cast; dyamic_cast when typeid is more appropriate is just a common operation used to determine "is of some type" in order to find the optimal interface of an object. Typeid, on the other hand, is a "tell me the actual type of object" operation to get the type of the object. The latter is bound to be simpler and faster. The latter (typeid) is easier to implement on its own if necessary (for example, if the working system forbids the use of RTTI for some reason), and generally speaking, the correct implementation of the former (dynamic_cast) is much more difficult.

Consider (consider):

Struct B {

Const char* name {"B"}

/ / if pb1- > id () = = pb2- > id () * pb1 is the same type as * pb2

Virtual const char* id () const {return name;}

/ /...

}

Struct D: B {

Const char* name {"D"}

Const char* id () const override {return name;}

/ /...

}

Void use ()

{

B* pb1 = new B

B* pb2 = new D

Cout id (); / / "B"

Cout id (); / / "D"

If (pb1- > id () = = "D") {/ / looks innocent

D* pd = static_cast (pb1)

/ /...

}

/ /...

}

The result of pb2- > id () = = "D" is actually an implementation decision. We added it to warn of the dangers of homemade RTTI. This code may work as expected for many years, but it will fail when it comes to a new machine, a new compiler, or a new connector without the literal amount of uniform characters.

Be careful if you implement RTTI on your own.

Exception (exception)

If your implementation provides a really slow dynamic_cast, you may have to work around it. However, all workarounds cannot be resolved statically and are prone to errors, including display type conversions (usually static_cast). You can only design dynamic_cast for special purposes. So, first make sure that your dynamic_cast is really as slow as you think (there are some unconfirmed rumors about it) and that the place where you use dynamic_cast is really that sensitive to performance.

We think the current implementation of dynamic_cast is a bit slow unnecessarily. For example, under the right conditions, dynamic_cast can be done in a very short fixed time. However, compatibility makes changes difficult, even if everyone agrees that optimization is valuable.

In very rare cases, if you have determined that the impact of dynamic_cast is real, you can use other ways to statically ensure that the downconversion will be successful (for example, you use CRTP carefully) and do not involve virtual inheritance, you can consider tactically using static_cast with obvious comments. However, because the type system can not verify the correctness, it is necessary to disclaim this code and remind it. Even to this extent, situations like "I know what I'm doing" are still a famous source of error in our experience.

Exception (exception)

Consider (consider the following code):

Template

Class Dx: B {

/ /...

}

Enforcement (implementation recommendations)

Indicates the use of static_cast for downward conversion, including the C style conversion of static_cast.

This rule is also part of the type safety rule group.

At this point, I believe you have a deeper understanding of "how C++ uses dynamic_cast". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report