Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is LLVM an exception to the rule for avoiding dynamic casts?

LLVM has it's own hand rolled alternative to RTTI that is a speed improvement over built-in RTTI and allows dynamic casting to classes with no vtable (dyn_cast). However, it can still be used in exactly the way that dynamic_cast<> is used though it does allow it to be used with more classes.

dyn_cast<> template documentation

LLVM is a reputable C++ project so this seems to fly in the face of the common saying that too many dynamic casts is a sign of bad design, also known as a code smell. Surely a better performing dynamic cast does nothing to improve its use in design than a standard dynamic_cast. So who is right here? Are there cases where large-scale use of dynamic casting is a good design choice in C++ code? Google turns up 690 occurrences of this kind of dynamic casting in the LLVM trunk source code.

Uses of dyn_cast<> in LLVM trunk

like image 786
a-dai Avatar asked Oct 23 '09 00:10

a-dai


1 Answers

While performance hits are a reason to avoid dynamic_cast<> for large class hierarchies, it's not the only reason you might want to avoid them. Better performing or not, one should not be more encouraged to use dyn_cast<> because of this claim.

On the other hand, there's absolutely nothing wrong with using dynamic_cast<> when it's the best tool for the job. If its use is justified, and the cleanest way to solve a problem, then it's always right, regardless of the "common saying".

I would certainly not steer clear of popular projects simply because they use dynamic_cast<>s, gotos or any other idiom that's fallen out of favour.

like image 139
Matt Joiner Avatar answered Oct 06 '22 01:10

Matt Joiner