Unreal C++ Cast<T> function and why you don't want to use static_cast for UObjects

Digging through forum posts about what kind of Cast<T> function to use I decided to write a short articleabout:

  • How Cast<T> works
  • Why Cast<T> is type-safe
  • How efficient Cast<T> in editor and non-editor environments
  • Cast<T> comparison with static_cast and dynamic_cast for UObjects
  • ExactCast<T> and CastChecked

TLDR:

  • Cast<T> has to be used for UObjects due to type safety; it will return nullptr in case of a failure in comparison with static_cast
  • Cast<T> runtime cost is O(1) or constant in non-editor environment and O(Depth(InheritanceTree)) in editor environment
  • Cast<T> does not use dynamic_cast.

I will be glad to hear your feedback!

P.S. Fixed the link :slight_smile:

3 Likes

Today is finally the day that I learn what Cast<T> does under the hood. Thanks for writing that up!