2

请注意以下代码。据我所知,dynamic_cast 比 static_cast 慢。因为它在运行时评估类型。我的疑问是,如果我们将 static_cast 与 typeid() 一起使用如下,它是否需要与动态转换相同的时间?它会比 dynamic_cast 更快吗?

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

使用 RTTI 进行静态转换:

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;

动态演员表:

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

s = &c;
Circle* cp = 0;
Square* sp = 0;
cp = dynamic_cast<Circle*>(s);
    if(cp != 0)
    cout << "It's a circle!" << endl;
sp = dynamic_cast<Square*>(s);
if(sp != 0)
    cout << "It's a square!" << endl;
4

4 回答 4

7

测试类型然后执行 更快static_cast,但是操作并不等效,因为这只会允许向下转换为最派生的类型(任何中间级别都不会与 匹配typeid)。我会使用dynamic_cast它,因为它更健壮(例如,如果有人扩展您的类型并传递指针,则不会中断)。

如果性能dynamic_cast是您的应用程序中的一个问题,您应该重新考虑设计。虽然typeid+static_cast比 快dynamic_cast,但不必打开对象的运行时类型比它们中的任何一个都快。

于 2012-09-25T18:28:39.127 回答
3

这些代码示例在逻辑上并不相同。您忘记了dynamic_cast将类继承纳入帐户,并且比较 typeid() 仅比较继承树的叶子部分。typeid 给你的唯一东西是“与该对象的实际类型相关的一些唯一标识符”。单独使用 typeid() 您无法检查是否可以强制转换为公共基的指针,您只能检查 runtimetype-of-that 是否与 runtimetype-of-otherthing 完全相同。

话虽如此,我认为 static_cast+typeid 在一般意义上应该更快一些,但在某些情况下只会给出错误的答案。

于 2012-09-25T17:56:18.873 回答
1

我想任何体面的编译器都能够将两个示例优化为相同的代码。但是,找出答案的唯一方法是测量特定工具链的结果。

于 2012-09-25T17:50:15.060 回答
0

只有一种方法可以确定。用 std::chrono 和high_resolution_clock测量它。

于 2012-09-25T17:42:52.043 回答