I noticed that compiler will optimize out some dynamic_cast when the following operation is non-polymorphic, for example the following code:
#include <iostream>
using namespace std;
struct A
{
virtual ~A() = default;
virtual int f()
{
return 1;
};
virtual int g() = 0;
};
struct B : A
{
int g() const
{
return 2;
}
int g() override
{
return 3;
}
int h()
{
return 4;
}
};
int main()
{
A* p = new B();
auto u = p->f();
auto v1 = static_cast<B*>(p)->f();
auto v2 = dynamic_cast<B*>(p)->f();
auto w = p->g();
auto x1 = static_cast<const B*>(p)->g();
auto x2 = dynamic_cast<B*>(p)->g();
auto x3 = dynamic_cast<const B*>(p)->g();
auto y = dynamic_cast<B*>(p)->h();
cout << u << v1 << v2 << w << x1 << x2 << x3 << y << endl;
delete p;
return 0;
}
There are only two dynamic_cast calls compiled with g++ -O2, that means that equals to static_cast, so should I always use dynamic_cast for downcast for no extra overhead to be considered?
p
was a function parameter? As I see, the compiler should have not emit any dynamic_cast for OP's code, and neither forp
-as-a-parameter version. – Definition