Typically, when casting Foo* to SubclassOfFoo*, we use static_cast
instead of dynamic_cast.

Why?

dynamic_cast<> has runtime overhead. It does however do really nice
things, like blow up in your face if Foo* is not in fact a object that
is SubclassOfFoo* (it could be OtherSubclassOfFoo*).

We have had one of these in the tree for approximately forever:
Field_blob* is not on the same branch as Field_varstring*, but has
been being cast to it in field_conv.cc for ever. It just "worked"
because the first member of Field_blob kinda made sense in that
codepath.

Monty pointed out that protobuf has their own down_cast that does the
check on debug builds (included below).

What are people's thoughts?

also see http://smolsky.net/index.php/2009/09/14/down_cast-v2

>From protobuf source:
// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
// always succeed.  When you downcast (that is, cast a pointer from
// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
// how do you know the pointer is really of type SubclassOfFoo?  It
// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
// when you downcast, you should use this macro.  In debug mode, we
// use dynamic_cast<> to double-check the downcast is legal (we die
// if it's not).  In normal mode, we do the efficient static_cast<>
// instead.  Thus, it's important to test in debug mode to make sure
// the cast is legal!
//    This is the only place in the code we should use dynamic_cast<>.
// In particular, you SHOULDN'T be using dynamic_cast<> in order to
// do RTTI (eg code like this:
//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
// You should design the code some other way not to need this.

template<typename To, typename From>     // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) {                   // so we only accept pointers
  // Ensures that To is a sub-type of From *.  This test is here only
  // for compile-time type checking, and has no overhead in an
  // optimized build at run-time, as it will be optimized away
  // completely.
  if (false) {
    implicit_cast<From*, To>(0);
  }

-- 
Stewart Smith

_______________________________________________
Mailing list: https://launchpad.net/~drizzle-discuss
Post to     : [email protected]
Unsubscribe : https://launchpad.net/~drizzle-discuss
More help   : https://help.launchpad.net/ListHelp

Reply via email to