In-depth: All the nuances of static_cast (and others)

March 16, 2012
In-depth: All the nuances of static_cast (and others)

[In this reprinted #altdevblogaday in-depth piece, Crytek technical lead Jaewon Jung offers some clarifications on C++ cast operators, and several conclusions based on his analysis.] Recently I noticed my knowledge about C++ cast operators had been far from complete. For instance, I had thought static_cast is only for static upcasts (or downcasts also?) in an inheritance hierarchy. And for some legitimate casts between primitive types(like between int and float or between int and unsigned int), I used the C-style cast, still. I was not sure about how new cast operators are precisely mapped to the old C-style, either. So here is my shot at finally clarifying all these. Categories Errors possible

  • Es : compile error

  • Er: run-time check failure

    • an exception when casting a reference

    • returing nullptr when casting a pointer

  • Ec : run-time crash when using the converted

Conversions supported

  • Cprim: between primitive types : int <-> float, int <-> unsigned int

    • built-in conversion rules apply

  • pointer(reference) types

    • Cbase: pointer to a linearly related type(upcast/downcast) : CDerived* <-> CBased*

      • a proper pointer arithmetic applies if a multiple inheritance used

    • Cvoid : void pointer : void* <-> int*

    • Cconst : removing const/volatile type qualifiers : const int* <-> int*

    • Cetc : Any other cases : int* <-> float*

Casts static_cast<>

  • Cprim, Cbase, Cvoid

  • Es if Cconst, Cetc tried

  • A possible Ec if an invalid downcast tried e.g. CBase* pB = new CBase(); CDerived* pD = static_cast(pB);

reinterpret_cast<>

  • Cbase

Tags:

No tags.

JikGuard.com, a high-tech security service provider focusing on game protection and anti-cheat, is committed to helping game companies solve the problem of cheats and hacks, and providing deeply integrated encryption protection solutions for games.

Explore Features>>