What are some 'good use' examples of dynamic casting?

后端 未结 6 2244
攒了一身酷
攒了一身酷 2020-12-09 03:29

We often hear/read that one should avoid dynamic casting. I was wondering what would be \'good use\' examples of it, according to you?

Edit:

Yes, I\'m aware

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 04:00

    It can be used for a bit of run-time type-safety when exposing handles to objects though a C interface. Have all the exposed classes inherit from a common base class. When accepting a handle to a function, first cast to the base class, then dynamic cast to the class you're expecting. If they passed in a non-sensical handle, you'll get an exception when the run-time can't find the rtti. If they passed in a valid handle of the wrong type, you get a NULL pointer and can throw your own exception. If they passed in the correct pointer, you're good to go. This isn't fool-proof, but it is certainly better at catching mistaken calls to the libraries than a straight reinterpret cast from a handle, and waiting until some data gets mysteriously corrupted when you pass the wrong handle in.

提交回复
热议问题