C ++: using typeid in production code

Is it generally considered bad practice to use typeid in production code? In addition, I noticed that typeid returns type_info , which includes some metadata (such as a string with a type name); is there any way to deactivate this?

+8
c ++ typeid
source share
2 answers

It is difficult to say whether the use of a particular language function is “bad” or “good”. It depends on how you use it. There is nothing wrong with using typeid if it is the right tool for the job, but if there is a better solution to any problem you are solving, then you should avoid using typeid in favor of this better solution.

Often it is not recommended to use typeid , because its use can often be avoided using inheritance and virtual functions. If you can upgrade your system this way, then this might be a good idea.

As for whether typeid can be avoided returning std::type_info , this should not cause performance issues. typeid is evaluated as const std::type_info& , therefore, it does not deeply copy any string information contained in it. Most implementations have the actual std::type_info object stored in the virtual function table of the object, so internal copying is not performed.

+8
source share
  • Depends on what you do with the type. If you use where you should use polymorphism, then of course this is bad. However, dropping traces or similar things for debugging on client machines is just fine.
  • The only way to disable RTTI on your compiler. There is no standard way to do this. Please note that this will also disable dynamic_cast .
+11
source share

All Articles