Mak*_*ane -2 c++ oop dynamic-cast subclassing
在C++中,"dynamic_cast"缓慢是一个众所周知的事实.我想到了以下简单的方法来了解层次结构中对象的类型.有人可以解释一下这是否比dynamic_cast慢?如果不是,那么为什么不是普遍的做法,因为速度的C++对C最差的缺点?
struct Base {
unsigned m_type;
Base(unsigned type): m_type(type) {}
Base(): m_type(0) {}
};
struct Derived1: Base {
Derived1(): Base(1) {}
Derived1(int type): Base(type) {}
};
struct Derived2: Base {
Derived2(): Base(2) {}
};
struct Derived3: Derived1 {
Derived3(): Derived1(3) {}
};
void my_func(Base * p) {
if (p - > m_type == 0) {}
else if (p - > m_type == 1) {}
else if (p - > m_type == 2) {}
else if (p - > m_type == 3) {}
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下这是否比dynamic_cast慢?
它可能比dynamic_cast'ing慢,当......
Base衍生对象是不可改变的,允许各种优化的,而你的类包含一个可变类型变量.另外,您是否真的检查过dynamic_cast相对于您可能正在做的其他事情有多慢?
为什么不是常见做法[?]
...鉴于速度是C++优于C的最大缺点?
事实并非如此.现在很有可能(并且很常见)用C语言编写性能更好的代码而不是C语言中的语义代码.
但无论如何,这应该无关紧要,因为你没有业务在性能关键代码中进行动态转换; 正如@NathanOliver在评论中所暗示的那样,这是一个设计缺陷.