c++ - 在每个实例的唯一虚拟 int type() 中使用静态转换来提高性能是否安全?

标签 c++ performance polymorphism dynamic-cast static-cast

我有一个密集的多态对象层次结构,每个对象都带有一个强制性的 virtual int type() = 0 方法,该方法是为每个对象手动编写的。

使用dynamic_cast 对树的“安全”处理有很大的开销,而且我已经有一个虚拟方法,它会为每个不同的类型返回一个唯一的整数,我认为它是安全的使用不安全的静态转换。但是我可能会忽略一些东西,例如在多重继承的情况下或其他可能导致错位的情况,这可能会导致静态转换“崩溃”?

层次结构由不同的上下文在基类级别遍历,每个上下文都有解释数据的自定义方式,因此对于每个对象都有 switch (type) 和“do according to type "进行类型转换的地方。

type() virtual 在“utmost-base-class”中声明,它在继承中始终排在第一位。

最佳答案

根据标准 5.2.9/2,您打算进行的静态转换是安全的,前提是基类不是虚拟基类,也不是虚基类的基类。

这里是标准中提供的示例:

struct B { };
struct D : public B { };
D d;
B &br = d;
static_cast<D&>(br); // produces lvalue to the original d object
// Note that this works because B is not a virtual base class

所以除非你使用虚拟基础的多重继承,否则没关系。

但是如果你有这样的想法要小心:

struct B { };
struct D1 : public virtual B { };
struct D2 : public virtual B {}; 
struct E : D1, D2 {};  
E e; 
B *pb=&e;   //
static_cast<E*>(pb);   // ouch !!! This would not safe 

D1 *pd1 = &e; 
static_cast<E*>(pd1);   // but this would be ok 

关于c++ - 在每个实例的唯一虚拟 int type() 中使用静态转换来提高性能是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27658695/

相关文章:

c# - 在 64 位下执行缓慢。可能是 RyuJIT 错误?

c++ - 在指针类中引用虚函数时出现段错误

c++ - 如何指向输入流?

performance - 在 Big-O 分析中计算 c 和 n 为零

visual-studio - 通过远程桌面的 VS 2008 SP1 : Constant Repainting?

java - 有关方法重写的问题

java - Java 中的转换(接口(interface)和类)

c++ - Waf:递归收集源文件并包含路径

java - 管理供 Java GUI 使用的 C++ API 的 Java 包装 : proper version control

C++ 将第二个元素添加到 BST - 段错误