Does casting a pointer to an instance of a d开发者_运维百科ervived class to the instances base class have any run-time overhead in C++, or is it resolved at compile-time?
If it does have any, what exactly has to be computed in the casting operation?
Example:
class Foo;
class Bar : public Foo;
Bar* y = new Bar;
Foo* x = (Foo*) y;
(I know I should use C++-style casts and that the answer is probably the same for them)
Yes, though it's negligible.
In this case, a C-Style cast is interpreted as a static_cast
, which may incur a pointer adjustment.
struct Base {};
struct Derived: Base { virtual ~Derived(); } // note: introduced a virtual method
int main()
{
Derived derived;
Base* b = &derived;
Derived* d = (Derived*) b;
void* pb = b;
void* pd = d;
printf("%p %p", pb, pd);
return 0;
}
This overhead happens whenever the base subobject is not aligned at the same address that the derived object, which happens when:
- introducing the first virtual method
- using multi-inheritance
Of course, pointer adjustment is usually counted as negligible, and the compiler shall be smart enough to eliminate it if it's unnecessary anyway (an adjustment of 0).
Note: this is implementation dependent, not mandated by the standard
Foo* x = (Foo*) y;
You don't need to cast Bar*
to Foo*
. Casting from Derived to Base is implicit:
Foo* x = y ; // is enough!
As for polymorphic cast, C-style cast is not equivalent to dynamic_cast
. C++ dynamic_cast
is completely a new feature added to the language, and has no match in C-style cast.
Does casting a pointer to an instance of a dervived class to the instances base class have any run-time overhead in C++, or is it resolved at compile-time?
Casting from derived to base is resolved at compile-time, if you do as I did above. So it has not runtime overhead.
C casts have no runtime overhead whatsoever. The only cast operation which creates runtime overhead is dynamic_cast<>()
as it checks runtime type information.
See the answer to a similar question: regular cast vs static cast vs dynamic cast
Summarized: a C-style cast has no run-time overhead as it tries a bunch of C++ casting methods except dynamic_cast
(which incurs a run-time penalty).
精彩评论