|
Boost : |
From: Kevlin Henney (Kevlin.Henney_at_[hidden])
Date: 1999-09-02 09:27:29
[...]
I thought "safe_downcast" was spelled "dynamic_cast". Seems about as
safe as static_cast, only it happens to be checked during debugging
(only). Safe to me implies what dynamic_cast provides, and nothing
less. Perhaps debug_static_cast (or something along those lines) would
be clearer?
Not quite: dynamic_cast supports cross casting and casting through
virtual base classes, whereas this is not the intent of safe_downcast.
However, as it probably now stands (I'm looking at code from
polymorphic_cast as was), it is not actually particularly safe. If
NDEBUG is set, I lose all of the compile time checking as well as the
runtime checking -- baby has been thrown out w/ the bath water! This
can be fixed, and at no extra execution cost, by adding a dummy
dynamic_cast that is parsed and checked, but is not executed and -- on
a good compiler -- will not have code gen'd for it either:
template<class Derived, class Base>
inline Derived safe_downcast(Base* x)
{
assert(dynamic_cast<Derived>(x) != 0);
if(false)
dynamic_cast<Derived>(x);
return static_cast<Derived>(x);
}
Thoughts?
Kevlin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk