Could somebody please elaborate on the differences?
A:
(int) foo compares most to c++ reinterpret_cast<int>
, i.e. no checks on the validity of the cast.
Fredrik Jansson
2009-01-24 10:11:26
http://www.velocityreviews.com/forums/t280611-reinterpretcastltgt-v-staticcastltgt.html expains the difference between static_cast and reinterpret_cast
Fredrik Jansson
2009-01-24 10:14:23
No, it compares to a combination of all the C++ casts. It'll perform the first type of cast that's valid.
jalf
2009-01-24 10:14:44
True, except for dynamic_cast is not included.
Fredrik Jansson
2009-01-24 10:21:11
Are you trying to say that the problem with (int)foo is that it probably falls through to reinterpret_cast<foo> most times? So you don't actually get the benefit of static type checking.
bmatthews68
2009-01-24 10:23:55
This answer is wrong. reinterpret_cast can, as other c++ casts, do only very little compared to a c-style cast.
Johannes Schaub - litb
2009-01-24 14:47:30
+8
A:
The difference is that (int)foo can mean half a dozen different things. It might be a static_cast (convert between statically known types), it might be a const_cast (adding or removing const-ness), or it might be a reinterpret_cast (converting between pointer types)
The compiler tries each of them until it finds one that works. Which means that it may not always pick the one you expect, so it can become a subtle source of bugs.
Further, static_cast is a lot easier to search for or do search/replace on.
jalf
2009-01-24 10:13:46
C-style casts can't do "safe" downcasting like dynamic_cast, only "unsafe" downcasting like static_cast.
bk1e
2009-01-24 17:12:53
Also, I put "safe" and "unsafe" in quotes because nothing in C++ is truly safe.
bk1e
2009-01-24 17:15:30
" (int)foo ... might be a dynamic_cast (downcasting to derived class)"Not true. (int)foo will never turn into a dynamic cast.
Suma
2009-01-24 17:50:59