gpt4 book ai didi

c++ - 用于遍历继承层次结构的 Static_cast 与 dynamic_cast

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:21 25 4
gpt4 key购买 nike

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

例子:

#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 才能使此类导航正常工作。只是动态转换要求类层次结构是多态的(即基类至少有一个虚函数)。
静态转换的这种效率增益从何而来?该书确实提到动态转换是进行类型安全向下转换的首选方法。

最佳答案

static_cast 本身 不需要 RTTI -- typeid 需要(和 dynamic_cast 一样),但是那是一个完全不同的问题。大多数强制转换只是告诉编译器“相信我,我知道我在做什么”——dynamic_cast 是个异常(exception),它要求编译器在运行时检查并可能失败。这就是巨大的性能差异!

关于c++ - 用于遍历继承层次结构的 Static_cast 与 dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1382540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com