Re: "Enable Run-time Type Information" by Doug
Doug
Mon Dec 15 16:27:55 CST 2003
fh1996 wrote:
>Doug Harrison [MVP] <dsh@mvps.org> wrote in message
>news:mk7stv40fvqcbfsi7in8srir2mtqammgld@4ax.com...
>> fh1996 wrote:
>>
>> >I tried checking/unchecking the checkbox of "Enable Run-time Type
>> >Information" and saw nothing affected with regards to using "typeid()"
>and
>> >related code. The code can still compile and run and provide with RTTI
>> >info.
>> >
>> >What gives with such setting under Project/Setting...?
>>
>> It only affects typeid and dynamic_cast on references or pointers to
>objects
>> of polymorphic types. Usage of typeid on non-polymorphic types can be
>> resolved statically, at compile-time. To see the difference, try compiling
>> this fragment with and without the virtual function.
>>
>> #include <typeinfo>
>>
>> struct X
>> {
>> virtual void f();
>> };
>>
>> struct Y : X
>> {
>> };
>>
>> void f(X* p)
>> {
>> X obj;
>> typeid(X);
This one always works, because an X is an X is an X. It can't be anything
else. It doesn't matter if you use /GR.
>> typeid(obj);
Even though X has a virtual function and is thus a polymorphic type, the
compiler knows for a fact that obj refers to an X. Therefore, it can
determine the type statically, and doesn't need /GR.
>> typeid(*p);
>> dynamic_cast<Y*>(p);
Here, the nature of the types matters, because the compiler doesn't know if
p points to an X, or the X part of a Y. For the polymorphic case, in which X
has a virtual function, this matters very much, because typeid is supposed
to return a type_info for the most derived object, which could be a Y. VC++
requires you to use the /GR compiler option to enable this behavior, because
it requires the compiler to emit type info data for all such classes, which
can grow your executable a bit. Typically, a pointer to this information is
stored in the class's vtbl.
Now, if X defined no virtual functions, then typeid would assume p points to
an X and would return a typeid for X, and the program would still compile.
However, the usage of dynamic_cast above requires X to be a polymorphic
type, and it's an error if it isn't. But if X is polymorphic, and you don't
specify /GR, the compiler warns you about both the typeid and the
dynamic_cast, because neither one may work as expected without /GR.
Confused? Just try compiling the sample at the command line, with and
without /GR, with and without the virtual function in X.
>> }
>>
>> --
>> Doug Harrison
>> Microsoft MVP - Visual C++
>
>Thank you very much!
>
>What do you mean by "polymorphic type"? Type of classes of virtual
>function(s)?
Yep.
>"Usage of typeid on non-polymorphic types can be resolved statically, at
>compile-time."
>Could you give an code example how this is realized?
Sure! See the annotations I added to my example above.
--
Doug Harrison
Microsoft MVP - Visual C++