Re: Casting always bad?
Carlos Moreno wrote:
I would venture to state as one of the very few unconditional,
absolute, no-exception rules, that C-style casts should *always*
be avoided, *at all cost*
I have 2 exceptions to that rule where I will use a C-style cast.
1. Casting a literal 0 (or NULL) to its type so the compiler knows what
overload to call.
Something like bar( ( foo * ) 0 ) rather than bar( static_cast<foo
*>(0) ); Code looks cleaner and I'm not really casting anything, I'm
simply writing a literal. In the new standard there will be nullptr but
I'm not sure if there will be a typed version.
2. Casting a const char * to const void * for the purpose of a cout
when I want to output the pointer, not the contents. The chances are
this is being done for debugging anyway.
4. The casting syntax was specifically designed by the C++ committee
in order to discourge casting. (this one surprises me)
And so it should -- I don't know if in some dark corner of the
committee's people's minds, there was this intention; it has
always been accepted that the main intention is that the casts
should stand out very obviously in the code -- also, with the
unique keywords involved in the syntax, you can *always* use
your editor's "Find" facility and find *all* the casts (which
would be troublesome if you use C-style cast (the text (int)
could be a parameter a function declaration)
As the FAQ says, casts are evil but an evil doesn't mean a never. I
have an object-loader system that uses dynamic_cast. The dynamic_cast
is in one place hidden away. Business level code should not be casting.
The object loader itself uses static_cast (I think, but it may be
reinterpret_cast). That is because it first calls dlsym which returns a
void*. My thread API also uses a static_cast from a void* because it
interacts with C. It then needs to use dynamic_cast to check that the
symbol (whose name was defined in a config file) really is of the type
that is required. If not then an exception is thrown.
If you program thin templates then you will also cast between void *
and T*. The code using the library is strongly typed but the library
itself is cutting corners because it knows it can.
Generally casts should be restricted to low-level infrastructural
libraries. Boost may use them because boost comes under that category.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]