none
What is the difference of safe_cast, static_cast & dynamic_cast?

    Question

  • Hi, I am using Visual C++ 2005 Express Edition. I'd like to know the difference between safe_cast, static_cast & dynamic_cast and also the proper usage?

     

    Thank you very much..

    Wednesday, January 23, 2008 1:49 AM

Answers

All replies

  • Hi~

    C++/CLI added new feature of type casting.

    It is a safe_cast.

    safe_cast guaranteed to produce verifiable MSIL.

    reference this page.

    http://msdn2.microsoft.com/en-us/library/23b7yy6w(VS.80).aspx

     

    static_cast and dynamic_cast was already existed in standard C++.

    static_cast is casting a type constrained type casting.

    dynamic_cast is for casting a inherited object's reference.

     

    Bye~

    Wednesday, January 23, 2008 3:19 AM
  • Do you have any example that show the proper usage?

     

    For now on, I have used quite a lot in my code but I just use it by trial so I tried it one by one. If safe_cast don't work, I tried static_cast or dynamic_cast.

     

    I want to know how to use it properly.

     

    Thank you very much there..

     

    Wednesday, January 23, 2008 7:17 AM
  • Hi,

    I'm fairly new to Visual C++ and have also been wondering about these cast operators. Here's what I think I've found out so far:

    • static_cast: includes no run-time checking, so is fast and potentially dangerous.

    • dynamic_cast: includes run-time checking, so is slow and safe. Returns a null pointer if the cast fails.

    • safe_cast: same as dynamic cast, but throws an exception if the cast fails. In addition, it produces "verifiable MSIL" whatever that means. :-)

    So far, I have only used safe_cast in my code. If safe_cast throws an exception, I think the right thing to do is to redesign the code - not switch to static_cast.
    • Edited by SincP Thursday, June 5, 2008 8:46 PM Minor layout change
    Thursday, June 5, 2008 8:45 PM