I have learned that using a C style cast is bad because if it crashes (I know that in this case this is super safe) we won’t know much about the problem, so we can do better, I suggest that we use a static_cast() from now on for this kind of issues, what do you guys think?
Mind refeshing my memory as to what you are referring to in the lecture? And why Unreal’s (Cast<T>()
) casting isn’t well suited?
The Cast<T>()
can not ‘crash’ but just returns a nullptr if it fails.
It is on you as coder to ensure (hint hint) and log the failed cast.
Protect your pointers
Sorry guys maybe I should have cleared this a bit more, what I mean about C style casting is something like this:
float ATank::GetHealthPercent() const
{
return (float)CurrentHealth / (float)StartingHealth;
}
Where we hard
cast the int type in this case to a float, the use of Unreal’s Cast<T>()
is safe to use, I’m aware of that @GamedevCala.
Ohhhhh, you mean the explicit type conversion.
I found this reference what is happening in that cast:
http://en.cppreference.com/w/cpp/language/explicit_cast
When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:
a) const_cast<new_type>(expression);
b) static_cast<new_type>(expression),
…
So it should be safe and your mentioned static_cast will be used by the compiler anyway, if the const_cast doesn’t work?
Oh ok nice, yes that solves my question, thanks a lot!