Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Using typeid in production code

Tags:

c++

typeid

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

like image 216
Paul Manta Avatar asked Jun 15 '11 23:06

Paul Manta


2 Answers

  1. Depends on what you're doing with the typeid. If you're using where you should use polymorphism, then of course that's bad. However, dumping out traces or things like that to debug on customers' machines is just fine.
  2. The only way is to disable RTTI on your compiler. There's no standard way of doing it. Note this will also disable dynamic_cast.
like image 161
Billy ONeal Avatar answered Nov 07 '22 15:11

Billy ONeal


It's hard to say whether the use of a particular language feature is "bad" or "good." It really depends on how you use it. There's nothing inherently wrong with using typeid if it's the right tool for the job, but if there's a better solution to whatever problem you're solving, then you should avoid using typeid in favor of that better solution.

It is often not a good idea to use typeid because its use can often be avoided by using inheritance and virtual functions. If you can update your system in this way, then it might be a good idea to do so.

As for whether you can have typeid avoid returning a std::type_info, this shouldn't cause any performance problems. typeid evaluates to a const std::type_info&, so it doesn't deep-copy any of the string information it contains. Most implementations have the actual std::type_info object stored in the object's virtual function table, so no copying is done internally.

like image 36
templatetypedef Avatar answered Nov 07 '22 15:11

templatetypedef