Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Nov 15, 2005

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<bar *>(this);  }
};

class mumble : public foo
{
public:

  virtual mumble *downcast_to_mumble()
  {  return static_cast<mumble *>(this);  }
};

class submumble : public mumble
{

  virtual submumble *downcast_to_submumble()
  {  return static_cast<submumble *>(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<bar *>(my_foo);
    }
    } else {
      for (long int i(1000000000); i > 0; --i)
    {
      my_bar = my_foo->downcast_to_bar();
    }
    }

  delete my_foo;

  return 0;
}
Dick King
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap