Safely Downcast Pointers Without dynamic_cast Overhead

Safely Downcast Pointers Without dynamic_cast Overhead

Suppose you have a class hierarchy and you plan to do some downcasts. Try writing virtuals in the root class to do the downcasting to NULL for each of the subclasses. Then, write each subclass so it downcasts to itself statically. I run Debian and gcc 3.4.3 on a modern Pentium, and I ran this test with optimization turned off (the loops might have disappeared with optimization turned on). In this example, the total runtime is eight times faster using the virtuals than dynamic_cast. Here’s an example:

class bar;class mumble;class submumble;class foo{public:  virtual bar *downcast_to_bar()  {  return NULL;  }  virtual mumble *downcast_to_mumble()  {  return NULL;  }  virtual submumble *downcast_to_submumble()  {  return NULL;  }};class bar : public foo{public:  virtual bar *downcast_to_bar()  {  return static_cast(this);  }};class mumble : public foo{public:  virtual mumble *downcast_to_mumble()  {  return static_cast(this);  }};class submumble : public mumble{  virtual submumble *downcast_to_submumble()  {  return static_cast(this);  }};int main (int argc, char **argv){  foo     *my_foo(new bar);  bar     *my_bar;  if (argc > 1)    {      for (long int i(1000000000); i > 0; --i)    {      my_bar = dynamic_cast(my_foo);    }    } else {      for (long int i(1000000000); i > 0; --i)    {      my_bar = my_foo->downcast_to_bar();    }    }  delete my_foo;  return 0;}
See also  How College Students Can Shape the Future of Tech Responsibility

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist