Static roll versus dynamic roll for passing inheritance hierarchy

I saw one book in C ++ that mentions that transitions to inheritance hierarchies using static casting are more efficient than using dynamic wrapping.

Example:

#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 a circle!" << endl;
    if(sp != 0)
        cout << "It 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
} ///:~

However, for dynamic translation and static casting (as implemented above) RTTI is enabled for such navigation. Just for dynamic translation to require that the class hierarchy be polymorphic (i.e. the Base class has at least one virtual function).
Where does this effectiveness for static casting come from? The book mentions that dynamic casting is the preferred method for Tibetan demotion.

+5
4

static_cast per se RTTI - typeid ( dynamic_cast), . : " , , " - dynamic_cast , , , . !

+9

, . , - :

class Shape {
public:
    virtual ~Shape() {};
    virtual void announce() = 0;  // And likewise redeclare in Circle and Square.
};

void Circle::announce() {
    cout << "It a circle!" << endl;
}

void Square::announce() {
    cout << "It a square!" << endl;
}

// Later...
s->announce();

, , .

: static_cast RTTI, , undefined (, ). dynamic_cast , , ( ) RTTI. C , static_cast, , static_cast .

+7

( ) ( , , ), . static_cast typeid , , :

, ,

, , , , , , , (?), static_cast dynamic_cast... , , , .

, rtti + static_cast, - , , , , CPU. , , ( ), , . , , , downcasts, , , j_random_hacker, , .

+5

dynamic_castreturns NULL if you did not perform a type check and could not succeed. static_castwill succeed (and lead to undefined behavior, such as a possible failure). This is probably the difference in speed.

+1
source

All Articles