I have a serious of if-else dynamic_cast to do downcast and perform specific subclass methods like the following. (I know using dynamic_cast may be considered something wrong in design.)
void cryout(const Animal* pAnimal)
{
if(!pAnimal){ return; }
...
if (auto pCat = dynamic_cast<const Cat*>(pAnimal))
{
pCat->meow();
}
else if (auto pDog = dynamic_cast<const Dog*>(pAnimal))
{
pDog->bark();
}
else
{
std::cerr << "No such animal.\n" ;
}
}
Then I want to change to let the parameter passed by reference to not worry about null pointer issue.
void cryout(const Animal& animal)
{
...
try
{
auto& cat = dynamic_cast<const Cat&>(animal);
cat.meow();
}
catch (std::bad_cast)
{
try
{
auto& dog = dynamic_cast<const Dog&>(animal);
dog.bark();
}
catch (std::bad_cast)
{
std::cerr << "No such animal.\n";
}
}
}
But this changes involve the stack unwinding when non-cat animal object passed in. AFAIK, stack unwinding could lead performance downgrade a lot. Is this casting by reference approach practical in my case?
BTW, isn't it strange to make "std::bad_cast exception" thrown in the normal working flow?
dynamic_cast<const Cat*>(&animal)
? – paddycryout
a method. But if I absolutely had to usedynamic_cast
, I would prefer the exception-free version for clarity. – paddydynamic_cast by reference
considered always succeeded or it will be a exceptional case. – Chen OT