开发者

c++ typeid operator

I am using Visual Studio 2005 Proffesional Edition.

In the following example SomeClass is class that is defined in third party dll library I am using. SomeClass has virtual methods. I noticed that the operator typeid gives dif开发者_开发百科ferent results when applied to the type itself, and when applied to object of the type. Is this normal behavior, and if not what could be the reason for such behavior?

typeid(SomeClass).raw_name()   // the value of this is   ".?AVSomeClass@@"
typeid(SomeClass).name()          ///  "class SomeClass"

SomeClass obj;
typeid(obj).raw_name(); // ".?AVTLomeClass@@"
typeid(obj).name();       // "class TLomeClass"


Is the code in your question the same or similar to the code you are having problems with?

Operator typeid, when it is applied to polymorphic types, returns the type_info object that identifies the dynamic type of the polymorphic object. So, for example, if you apply typeid to a reference of type Base & (where Base is polymorphic), which is actually bound to an object of type Derived (where Derived is derived from Base), the type_info object returned by typeid will correspond to the Derived class, not to Base class. Could it be that something like that is happening in your code?

Also, in some compilers (like MS Visual Studio) in order to use fully-functional typeid, as described above, you need to compile your code with Run-Time Type Information (RTTI) enabled. Maybe the absence of RTTI led to the strange effects you observed.

P.S. Contrary to what is stated in the currently accepted answer, typeid is fully and perfectly standard C++ feature. It is not a compiler extension.


The reason for this behavior is documented somewhere on MSDN. The specific behavior you're seeing in this particular case is probably due to some use of inheritance, or some compiler extension, not documented by the .DLL's vendor.

The operator's behavior is not defined by the C++ standard, and as such is a compiler extension. You can not rely on its behavior, nor can you have any reasonable expectation of finding out why it does what it does in the way that it does, unless it's explicitly documented by the vendor. Its behavior may have changed in VS2008, and likely differs from VS2003. (It certainly differs from GCC, ICC, and various other compilers.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜