c++ - Why use static_cast<int>(x) instead of (int)x? -


i've heard static_cast function should preferred c-style or simple function-style casting. true? why?

the main reason classic c casts make no distinction between call static_cast<>(), reinterpret_cast<>(), const_cast<>(), , dynamic_cast<>(). these 4 things different.

a static_cast<>() safe. there valid conversion in language, or appropriate constructor makes possible. time it's bit risky when cast down inherited class; must make sure object descendant claim is, means external language (like flag in object). dynamic_cast<>() safe long result checked (pointer) or possible exception taken account (reference).

a reinterpret_cast<>() (or const_cast<>()) on other hand dangerous. tell compiler: "trust me: know doesn't foo (this looks if isn't mutable), is".

the first problem it's impossible tell 1 occur in c-style cast without looking @ large , disperse pieces of code , knowing rules.

let's assume these:

class cmyclass : public cmybase {...}; class cmyotherstuff {...} ;  cmybase  *psomething; // filled somewhere 

now, these 2 compiled same way:

cmyclass *pmyobject; pmyobject = static_cast<cmyclass*>(psomething); // safe; long checked  pmyobject = (cmyclass*)(psomething); // same static_cast<>                                      // safe; long checked                                      // harder read 

however, let's see identical code:

cmyotherstuff *pother; pother = static_cast<cmyotherstuff*>(psomething); // compiler error: can't convert  pother = (cmyotherstuff*)(psomething);            // no compiler error.                                                   // same reinterpret_cast<>                                                   // , it's wrong!!! 

as can see, there no easy way distinguish between 2 situations without knowing lot classes involved.

the second problem c-style casts hard locate. in complex expressions can hard see c-style casts. virtually impossible write automated tool needs locate c-style casts (for example search tool) without full blown c++ compiler front-end. on other hand, it's easy search "static_cast<" or "reinterpret_cast<".

pother = reinterpret_cast<cmyotherstuff*>(psomething);       // no compiler error.       // presence of reinterpret_cast<>        // siren red flashing lights in code.       // mere typing of should cause feel uncomfortable. 

that means that, not c-style casts more dangerous, it's lot harder find them make sure correct.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -