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;}
Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular