Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do polymorphic C-style casts have any overhead?

  • 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?

  • 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)

like image 410
Richard Simons Avatar asked Dec 13 '22 15:12

Richard Simons


1 Answers

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

like image 182
Matthieu M. Avatar answered Dec 29 '22 19:12

Matthieu M.