Is LLVM an exception to the rule for excluding dynamic throws?

LLVM has its own manual alternative to RTTI, which is a speed improvement over the built-in RTTI and allows dynamic casting to classes without vtable ( dyn_cast ). However, it can still be used exactly as dynamic_cast<> , although it allows it to be used with a large number of classes.

dyn_cast<> template documentation

LLVM is a reputable C ++ project, so it seems to be confronted with the general saying that too many dynamic throws are a sign of poor design, also known as code smell. Of course, a more effective dynamic emphasis does not improve its use in design than the standard dynamic_cast . So who is here? Are there cases where widespread use of dynamic cast is a good design choice in C ++ code? Google calls 690 occurrences of such a dynamic cast in the LLVM trunk source code.

Using dyn_cast<> on the LLVM dyn_cast<>

+6
c ++ design-patterns dynamic-cast llvm
source share
3 answers

While performance hits are a reason to avoid dynamic_cast<> for a hierarchy of large classes, this is not the only reason you might want to avoid them. Because of this requirement, it is better not to use dyn_cast<> .

On the other hand, there is nothing wrong with using dynamic_cast<> when it is the best tool to work with. If its use is justified and the cleanest way to solve the problem, then he is always right, regardless of the "general statement".

Of course, I would not have avoided popular projects simply because they used dynamic_cast<> s, goto or any other idiom that fell out of hostility.

+7
source share

I think that casting the dynamics is bad, not because they are slow, but because they mean that your code is too tightly coupled.

+1
source share

I just looked very quickly at the implementation of dyn_cast and isa in the LLVM documentation.

The code instance has the following:

 struct bar { bar() {} private: bar(const bar &); }; struct foo { void ext() const; /* static bool classof(const bar *X) { cerr << "Classof: " << X << "\n"; return true; }*/ }; template <> inline bool isa_impl<foo,bar>(const bar &Val) { errs() << "Classof: " << &Val << "\n"; return true; } 

The test is called using B and has:

 if (!isa<foo>(B1)) return; if (!isa<foo>(B2)) return; 

If I understand correctly what is going on correctly, the isa template (which is used by dyn_cast ) uses the explicit specialization of isa_impl to reference the panel with foo. In the above examples, it seems that isa<foo>(B1) returns true!

In any case, this is very different from the dynamic_cast behavior, so I really don't think you can compare them with each other.

Obviously, I can misunderstand what LLVM does, so please let me know if I do not understand the code!

-one
source share

All Articles