静态转换与用于遍历继承层次结构的dymamic转换 [英] Static cast vs. dymamic cast for traversing inheritance hierarchies

查看:107
本文介绍了静态转换与用于遍历继承层次结构的dymamic转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一本关于C ++的书,提到使用静态转换导航继承层次结构比使用动态转换更有效。

I saw one book on C++ mentioning that navigating inheritance hierarchies using static cast is more efficient than using dynamic cast.

示例:

#include <iostream>
#include <typeinfo>

using namespace std;

class Shape { public: virtual ~Shape() {}; };
class Circle : public Shape {};
class Square : public Shape {};
class Other {};

int main() {
    Circle c;

    Shape* s = &c; // Upcast: normal and OK

    // More explicit but unnecessary:
    s = static_cast<Shape*>(&c);
    // (Since upcasting is such a safe and common
    // operation, the cast becomes cluttering)

    Circle* cp = 0;
    Square* sp = 0;

    // Static Navigation of class hierarchies
    // requires extra type information:
    if(typeid(s) == typeid(cp)) // C++ RTTI
        cp = static_cast<Circle*>(s);
    if(typeid(s) == typeid(sp))
        sp = static_cast<Square*>(s);
    if(cp != 0)
        cout << "It's a circle!" << endl;
    if(sp != 0)
        cout << "It's a square!" << endl;

    // Static navigation is ONLY an efficiency hack;
    // dynamic_cast is always safer. However:
    // Other* op = static_cast<Other*>(s);
    // Conveniently gives an error message, while
    Other* op2 = (Other*)s;
    // does not
} ///:~

动态转换和静态转换(如上面实现的)需要RTTI使这种导航工作。这只是动态转换要求类层次结构是多态的(即基类至少有一个虚函数)。

静态转换的效率增益是从哪里来的?
本书确实提到了动态转换是进行类型安全向下转换的首选方法。

However, both dynamic cast and static cast (as implemented above) need RTTI enabled for such navigation to work. It's just that dynamic cast requires the class hierarchy to be polymorphic (i.e. base class having at least one virtual function).
Where does this efficiency gain for static cast come from? The book does mention that dynamic cast is the preferred way for doing type-safe downcasting.

推荐答案

static_cast 本身不需要RTTI - typeid > dynamic_cast ),但这是一个完全不同的问题。大多数cast只是告诉编译器相信我,我知道我在做什么 - dynamic_cast 是例外,它要求编译器在运行时检查,可能失败。这是那里的巨大的性能差异!

static_cast per se DOESN'T need RTTI -- typeid does (as does dynamic_cast), but that's a completely different issue. Most casts are just telling the compiler "trust me, I know what I'm doing" -- dynamic_cast is the exception, it asks the compiler to check at runtime and possibly fail. That's the big performance difference right there!

这篇关于静态转换与用于遍历继承层次结构的dymamic转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆