How fast is dynamic_cast<>

后端 未结 2 929
北荒
北荒 2021-02-14 15:13

... approximately compared to a typical std::string::operator==()? I give some more details below, I\'m not sure if they are of any relevance. Answer with complexit

2条回答
  •  面向向阳花
    2021-02-14 15:59

    The best answer is to measure, my guess would be that dynamic_cast is faster than comparing any but the shortest strings (or perhaps even than short strings).

    That being said, trying to determine the type of an object is usually a sign of bad design, according to Liskov's substitution principle you should just treat the object the same and have the virtual functions behave the correct way without examining the type from the outside.


    Edit: After re-reading your question I'll stick to There is no sub-class to the one I'll be looking for. In that case you can use typeid directly, I believe it should be faster than either of your options (although looking for a specific type is still a code smell in my opinion)

    #include 
    #include 
    
    struct top {
        virtual ~top() {} 
    };
    
    struct left : top { };
    struct right : top { };
    
    int main()
    {
        left lft;
        top &tp = lft;   
        std::cout << std::boolalpha << (typeid(lft) == typeid(left)) << std::endl; 
        std::cout << std::boolalpha << (typeid(tp) == typeid(left)) << std::endl; 
        std::cout << std::boolalpha << (typeid(tp) == typeid(right)) << std::endl; 
    }
    

    Output:

    true
    true
    false

提交回复
热议问题