August 7, 2009

C++/CLI Casting Basics

C++/CLI Casting Basics
  • reinterpret_cast<> unsafe standard C++ cast
  • static_cast<> relies only on compile time information
  • const_cast<> is used to remove the const, volatile, and __unaligned
  • dynamic_cast<> relies both on compile time and run time information. if the cast is unsafe then this the cast returns NULL
  • __try_cast<> same as dynamic cast except it throws an exception if the cast fails
Recommendation for downcasting

If you are absolutely sure that the cast is going to be safe, you can use any of the four cast operators above, but I'd suggest that you use static_cast because that'd be the most efficient way of casting. If you are even a microscopic percentage unsure as to the safety of your cast, you must simply *avoid* static_cast and reinterpret_cast both of which are quite dangerous here. You may use either dynamic_cast or __try_cast depending on whether you like to check for NULL or you like to have an exception raised and handled.

Recommendations for upcasting

In most situations upcasting should be quite safe except when you have a bad derived class pointer (bad in the sense that it points to the wrong object). Therefore my recommendation for upcasting is to use static_cast which should be the most efficient. If your upcasts are unsafe it's probably time for you to sit down and figure out what's going wrong in your code rather than using dynamic_cast or __try_cast. In addition keep in kind that upcasting would probably be implicitly done in most situations.

No comments: