实现类的标识符或使用dynamic_cast
Implement an identifier for a class or use dynamic_cast
我的问题与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。
如果这确实是一个性能瓶颈,那么将Dog
和Cat
声明为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
的昂贵调用。一旦您对运行时进行了调用,您就会失败。
如果在Dog
和Cat
上都使用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
的实现并没有领会到这一暗示。
- 如何理解C++标准N3337中的expr.const.cast子句8
- C++Cast运算符过载
- 在成员dynamic_bitset上使用 boost::from_block_range 时出错,但在本地dynamic
- C++类中的二维"dynamic"数组?
- 错误:"cast"未命名类型void setCastDescription(std::string
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- protobuf in C++ with dynamic binding for google::protobuf::M
- 警告的原因是什么:"when type is in parentheses, array cannot have dynamic size"?
- C++:"Expected '(' for function-style cast or type construction"错误
- 为什么选择 g++ 给予者:"error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]"
- CUDA 错误:"dynamic initialization is not supported for __device__, __constant__ and __shared__ variabl
- Gtk+ g_signal_connect() 和 C++ lambda 会导致"invalid cast"错误
- 如何修复'The procedure entry point SDL_RWclose could not be located in the dynamic link library'
- Shared_ptr cast vs static_cast speed
- 在 iOS 上使用 Aruco 构建 OpenCV 时"Functional-style cast from id to double is not allowed"
- "The ordinal 344 could not be located in the dynamic link library"
- 覆盖 CAST 运算符(我认为它被称为向下转换)
- Dynamic Cast C++ Fail
- dynamic-cast-c++dynamic_cast错误处理