Re: Idiom: identical const and non-const methods
Alf P. Steinbach wrote:
* Greg Herlihy:
Because using a const_cast in a program is (at worst) potentially
dangerous
and (at best) not even needed, it's safe to say that a const_cast
(aka
"the
conversion of death") is probably best avoided.
Urgh. A static_cast is supposed to be preferable to a const_cast
because "the programmer has to evaluate ... each [const_cast] ... to
draw up ... list of unsafe casts". Hello.
I don't think Greg was advocating the use of a static_cast to add const.
The function that started all this was
Item& Container::find(const Key& key)
{
return const_cast<Item&>(
const_cast<const Container*>(this)->find(key));
}
If you rewrite this to use an intermediate reference, you can add the
const without using any cast at all.
Item& Container::find(const Key& key)
{
const Container& self = *this;
return const_cast<Item&>(self.find(key));
}
In this version, const_cast<> is used only for the (potentially unsafe)
operation of removing const.
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]