0

This is a question of pure curiosity, I don't think the answer could cause great improvements.

Let suppose there is this tree of inheritance:

           A
          / \
         /   \
       AB     AC
      /\       /\
  ABB  ABC   ACB ACC 

I have to write a function that executes differents actions basing on the object type. I'm 100% sure that this object can only be an AC object or one of its childs.

now which code is faster:

 int t = getObjectType();
 A*  obj = getObject();
 switch (t) {
      case 0:
         ACB* casted_obj = static_cast<ACB*>(obj);
      case 1:
         ACC* casted_obj = static_cast<ACC*>(obj);
 }

or

 int t = getObjectType();
 A*  sup = getObject();
 AC* obj = static_cast<AC*>(sup);
 switch (t) {
      case 0:
         ACB* casted_obj = static_cast<ACB*>(obj);
      case 1:
         ACC* casted_obj = static_cast<ACC*>(obj);
 }

Probably C++ standards doesn't say anything about how the tree of inheritance must be managed, so the answer depends on the implementation.

4

1 回答 1

2

Static casts are done entirely at compile time, so the performance impact will always be zero. The only type cast done at run time is dynamic_cast. More: http://www.cplusplus.com/doc/tutorial/typecasting/

于 2012-07-26T13:41:05.177 回答