c++ - Dynamic_cast 兼容性?

标签 c++ casting dynamic-cast

我正在阅读有关 dynamic_cast 的内容,然后我遇到了以下语句 ( from cplusplus.com ):

Compatibility note: This type of dynamic_cast requires Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This needs to be enabled for runtime type checking using dynamic_cast to work properly with these types.

例子之后:

// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";

    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}

作者所说的“这种类型的 dynamic_cast”是什么意思? dynamic_cast 不是只用于多态类吗(几乎)?他提到这个 RTTI 是动态转换工作所必需的,这是否意味着您必须谨慎使用 dynamic_cast 因为您不知道编译器是否完全支持它,因此它比其他转换风险更大哪些运营商不需要这个RTTI?

最佳答案

兼容性说明与前一段(和代码示例)相关:

But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is a valid complete object of the target type.

这是真的:向下转型需要一个多态类型的对象,并且 RTTI 在运行时遍历对象的继承树。

另一种类型的dynamic_castthat之前的段落中有解释:

This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the same way as allowed as an implicit conversion.

这里不需要 RTTI,因为对象的基总是静态已知的。

所以你只需要完整地阅读周围的文字,就能理解你正在阅读的单词的上下文。

但是,我要指出,根据我的经验,默认情况下禁用 RTTI 的编译器基本上是闻所未闻的。我并不是说不存在 - 可能有一些针对嵌入式平台的特定行业的利基编译器这样做是为了在程序员的 Makefile 中节省几个字节。但据我所知,大多数人使用的编译器(GCC、Clang、Visual Studio、ICC、Comeau)都将 RTTI 作为标准打包并保持打开状态,直到您要求将其关闭。

关于c++ - Dynamic_cast 兼容性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44444847/

相关文章:

c# - C#中的自动类型转换

c++ - dynamic_cast<> 失败但 static_cast<> 有效

c++ - 提取骨架中的连接点

c++ - 使用 C++11 正则表达式匹配文本范围

c++ - 固定长度的大整数

c# - 为什么在方法定义中使用 "Where"子句

c++ - 套接字编程,检查入口UDP缓冲区是否为空?

MySQL/MariaDB 混合数据类型排序

ios - swift 中的 Dynamic Cast Class Unconditional 问题

android - 如何在 Android 中使用 dynamic_cast 修复编译错误?