开发者

C++: Using typeid in production code

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


  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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜