实现类的标识符或使用dynamic_cast

Implement an identifier for a class or use dynamic_cast

本文关键字:dynamic cast 标识符 实现      更新时间:2023-10-16

我的问题与What';IsA()在C++中的作用点是什么?。我有一个性能关键代码,它在某个位置包含对派生类中特定函数的处理,其中只有基指针可用。检查我们拥有哪个派生类的最佳方法是什么?我已经编码了两个选项,在第二个选项中,我可以消除Animal_type枚举和get_type()函数。

#include <iostream>
enum Animal_type { Dog_type, Cat_type };
struct Animal
{
    virtual Animal_type get_type() const = 0;
};
struct Dog : Animal
{
    void go_for_walk() const { std::cout << "Walking. Woof!" << std::endl; }
    Animal_type get_type() const { return Dog_type; }
};
struct Cat : Animal
{
    void be_evil() const { std::cout << "Being evil!" << std::endl; }
    Animal_type get_type() const { return Cat_type; }
};
void action_option1(Animal* animal)
{
    if (animal->get_type() == Dog_type)
        dynamic_cast<Dog*>(animal)->go_for_walk();
    else if (animal->get_type() == Cat_type)
        dynamic_cast<Cat*>(animal)->be_evil();
    else
        return;
}
void action_option2(Animal* animal)
{
    Dog* dog = dynamic_cast<Dog*>(animal);
    if (dog)
    {
        dog->go_for_walk();
        return;
    }
    Cat* cat = dynamic_cast<Cat*>(animal);
    if (cat)
    {
        cat->be_evil();
        return;
    }
    return;
}
int main()
{
    Animal* cat = new Cat();
    Animal* dog = new Dog();
    action_option1(cat);
    action_option2(cat);
    action_option1(dog);
    action_option2(dog);
    return 0;
}

这在很大程度上取决于您的性能关键代码对性能的关键程度。我见过一些设置中,即使是虚拟功能的动态调度也过于昂贵,所以如果您处于这样的领域,请忘记dynamic_cast,手工制作一些东西。

不过,我认为你可以打一两个虚拟电话。您可能希望避开dynamic_cast,因为这通常比动态调度慢得多。

现在,代码中有从公共基派生的N类和M点,需要根据具体派生类做出决定。问题是:N,M中的哪一个在未来更有可能发生变化?您是否更有可能添加新的派生类,或者在类型决策很重要的地方引入新的点?这个答案将决定最适合你的设计。

如果您要添加新的类,但类型区分位置的数量是固定的(理想情况下也很小),那么枚举方法将是最好的选择。只需使用static_cast而不是dynamic_cast;如果知道实际的运行时类型,则不需要访问RTTI来为您进行转换(除非涉及虚拟基和更深层次的继承)。

另一方面,如果列表类是固定的,但可能会引入新的类型区分操作(或者如果它们太多而无法维护),则考虑Visitor模式。为您的Animal类提供虚拟访客接受功能:

virtual void accept(AnimalVisitor &v) = 0;
struct AnimalVisitor
{
  virtual void visit(Dog &dog) = 0;
  virtual void visit(Cat &cat) = 0;
};    

然后,每个派生类都将实现它:

void Dog::accept(AnimalVisitor &v)
{
  v.visit(*this);
}
void Cat::accept(AnimalVisitor &v)
{
  v.visit(*this);
}

你的运营部门只会使用它:

void action(Animal *animal)
{
  struct Action : AnimalVisitor
  {
    void visit(Dog &d) override { d.go_for_walk(); }
    void visit(Cat &c) override { c.be_evil(); }
  };
  AnimalVisitor v;
  animal->accept(v);
}

如果你要添加新的派生类和新的操作,你可以向上面的访问者添加非抽象函数,这样不需要知道新类的现有代码就不会中断:

struct AnimalVisitor
{
  virtual void visit(Dog &d) = 0;
  virtual void visit(Cat &c) = 0;
  virtual void visit(Parrot &p) {}
};

我想引用您引用的问题的公认答案:

在现代C++中没有意义。

对于您的示例,最简单的解决方案是使用动态调度:

struct Animal {
    virtual void action() = 0;
};
struct Dog{
    virtual void action()  { std::cout << "Walking. Woof!" << std::endl; }
};
struct Animal {
    virtual void action()  { std::cout << "Being evil!" << std::endl; }
};
int main()
{
    Animals* a[2] = {new Cat(), new Dog()};
    a[0]->action();
    a[1]->action();
    delete a[0];
    delete a[1];
    return 0;
 }

对于更复杂的场景,您可以考虑设计模式,如Strategy、Template Method或Visitor。

如果这确实是一个性能瓶颈,那么将DogCat声明为final可能会有所帮助。

您的第一个选项会更快,但前提是您修复了错误的dynamic_cast(应该是static_cast):

void action_option1_fixed(Animal* animal)
{
    if (animal->get_type() == Dog_type)
        static_cast<Dog*>(animal)->go_for_walk();
    else if (animal->get_type() == Cat_type)
        static_cast<Cat*>(animal)->be_evil();
}

get_type()上使用手动调度的要点是,它允许避免在C++运行时中对__dynamic_cast的昂贵调用。一旦您对运行时进行了调用,您就会失败。

如果在DogCat上都使用final限定符(即,在程序中您知道永远不会有子类的每个类上),则将有足够的信息来知道

dynamic_cast<Dog*>(animal)

可以实现为简单的指针比较;但遗憾的是(截至2017年)GCC和Clang都没有实现这样的优化。您可以使用C++typeid运算符手动进行优化,而无需引入get_type方法

void action_option3(Animal* animal)
{
    static_assert(std::is_final_v<Dog> && std::is_final_v<Cat>, "");
    if (typeid(*animal) == typeid(Dog))
        static_cast<Dog*>(animal)->go_for_walk();
    else if (typeid(*animal) == typeid(Cat))
        static_cast<Cat*>(animal)->be_evil();
}

使用clang++ -std=c++14 -O3 -S编译应该会向您展示第三种方法的好处。

action_option1启动

    movq    %rdi, %rbx
    movq    (%rbx), %rax
    callq   *(%rax)
    cmpl    $1, %eax
    jne     LBB0_1
    movq    __ZTI6Animal@GOTPCREL(%rip), %rsi
    movq    __ZTI3Dog@GOTPCREL(%rip), %rdx
    xorl    %ecx, %ecx
    movq    %rbx, %rdi
    callq   ___dynamic_cast
    movq    %rax, %rdi
    addq    $8, %rsp
    popq    %rbx
    popq    %rbp
    jmp     __ZNK3Dog11go_for_walkEv ## TAILCALL

action_option1_fixed将其改进为

    movq    %rdi, %rbx
    movq    (%rbx), %rax
    callq   *(%rax)
    cmpl    $1, %eax
    jne     LBB2_1
    movq    %rbx, %rdi
    addq    $8, %rsp
    popq    %rbx
    popq    %rbp
    jmp     __ZNK3Dog11go_for_walkEv ## TAILCALL

(请注意,在固定版本中,对__dynamic_cast的调用已经消失,取而代之的是一个小的指针数学)。

action_option2实际上比action_option1短,因为它没有在__dynamic_cast的之上添加虚拟调用,但它仍然很糟糕:

    movq    %rdi, %rbx
    testq   %rbx, %rbx
    je      LBB1_3
    movq    __ZTI6Animal@GOTPCREL(%rip), %rsi
    movq    __ZTI3Dog@GOTPCREL(%rip), %rdx
    xorl    %ecx, %ecx
    movq    %rbx, %rdi
    callq   ___dynamic_cast
    testq   %rax, %rax
    je      LBB1_2
    movq    %rax, %rdi
    addq    $8, %rsp
    popq    %rbx
    popq    %rbp
    jmp     __ZNK3Dog11go_for_walkEv ## TAILCALL

这是action_option3。它足够小,我可以把整个函数定义粘贴在这里,而不是摘录:

__Z14action_option3P6Animal:
    testq   %rdi, %rdi
    je      LBB3_4
    movq    (%rdi), %rax
    movq    -8(%rax), %rax
    movq    8(%rax), %rax
    cmpq    __ZTS3Dog@GOTPCREL(%rip), %rax
    je      LBB3_5
    cmpq    __ZTS3Cat@GOTPCREL(%rip), %rax
    je      LBB3_6
    retq
LBB3_5:
    jmp     __ZNK3Dog11go_for_walkEv ## TAILCALL
LBB3_6:
    jmp     __ZNK3Cat7be_evilEv     ## TAILCALL
LBB3_4:
    pushq   %rbp
    movq    %rsp, %rbp
    callq   ___cxa_bad_typeid

最后的CCD_ 28崩溃是因为可能是CCD_。您可以通过使参数类型为Animal&而不是Animal*来消除这种缺陷,这样编译器就知道它不是null。

我试着在函数的顶部添加这一行:

if (animal == nullptr) __builtin_unreachable();

但遗憾的是,Clang对typeid的实现并没有领会到这一暗示。