您的位置:首页 > 其它

整理: RTTI的设置, 含义, 用途

2011-02-01 14:39 190 查看
RTTI没有设置, 会使多态时强转过来的类指针没有指到正确的类, 引起程序崩溃.

因为和代码无关, 初看起来有些奇怪.



RTTI的设置: 以vs6和vs2010为例







RTTI含义

n programming, RTTI (Run-Time Type Information, or Run-Time Type Identification) refers to a C++ system that keeps information about an object's data type in memory at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. This is a C++ implementation of a more generic concept called reflection or, more specifically, type introspection.
In the original C++ design, Stroustrup did not include run-time type information, because he thought this mechanism was frequently misused
In order for the dynamic_cast<> operation, the typeid operator or exceptions to work in C++, RTTI must be enabled.
With C++ run-time type information, you can perform safe typecasts and manipulate type information at run time.
RTTI is only available for classes which are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.





RTTI用途: 为了使多态的类转换时, 能强转到正确的类指针上.

INTERNAL_ELEMENT* rawElem = dynamic_cast<INTERNAL_ELEMENT*>(((INTERNAL_NODE*)node->GetInternalNode()));



如果使用了dynamic_cast, 就要设置RTTI, 必须的

dynamic_cast < type-id > ( expression )
The expression dynamic_cast< type-id >( expression ) converts the operand expression to an object of type type-id. The type-id must be a pointer or a reference to a previously defined class type or a "pointer to void". The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.





编译时如果出现"warning C4541: 'dynamic_cast' ...", 就说明没有设置RTTI.

这个警告如果用 #pragma warning(disable : 4541)屏蔽掉, 出现的运行时错误还真不好理解.



<2011_0201_1459>

如果需要强转的类在DLL中, 必须使这个DLL也设置RTTI重新编译一次.

只在调用者处设置RTTI是没用的, 例如: xerces-c_2_8.dll
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: