static_cast does not give you information about success. If you need to do dynamic type casting use dynamic_cast or a library like boost any.
C++ proper way to static_cast
-
11-04-2022 - |
Domanda
static_cast
will not throw an exception. But if it does not succeed, it will produce a undefined result. What is the most proper way to check whether the cast succeeded?
Will this help?
NewType new_typ_obj = static_cast<NewType>(obj);
if (new_typ_obj)
new_typ_obj.do();
Soluzione
Altri suggerimenti
In the example you give, that static_cast
could throw an exception depending on the types involved, for example if the constructor of NewType
throws. If there doesn't exist any conversion chain from the type of obj
to NewType
, then it won't even compile.
You may be thinking of using static_cast
to convert a pointer-to-base into a pointer-to-derived, which is the case that dynamic_cast
checks. There's no way to tell whether static_cast
succeeds in that case. It's your responsibility as the programmer to only use it if it's correct.
A static_cast
only has undefined behaviour when you are casting between pointer, reference, or pointer to member types. It occurs when you perform a downcast to a type that is not truly the type of the object pointed at.
In your example, unless NewType
is a typedef of a pointer or reference type and obj
is also of those types, the compiler will give you an error if the cast is invalid.
Performing if (new_typ_obj)
does not make sense for checking whether the cast was successful in any static_cast
case. If NewType
is not one of these polymorphic types, then using new_type_obj
as a condition only works if you have some way to convert it to bool
(or it is bool
). Even if it does, it has nothing to do with the cast. If instead you are static_cast
ing through pointers to an inheritance hierarchy, then static_cast
will not give you any information about whether it succeeded. For that, you want dynamic_cast
.
static_cast
will not compile if the type you want to cast is not related to the type you want to cast into. Except with void *
that is related to all types. Thus static_cast is still a great assurance, at compile time.
There is still the danger of doing a wrong downcast.
My personal rule is to:
- prefer using static_cast for upcast, ( show the intent )
- prefer using dynamic_cast for downcast, and checking the returned value.
The latter rule can be done away with if the static_cast for a downcast is dangerless.