Re: converting a char* to a const char*
On Aug 7, 1:28 am, Juha Nieminen <nos...@thanks.invalid> wrote:
James Kanze wrote:
You have got it backwards: const_cast is used to *remove*
constness, not to add it.
Usually. It can be used either way, and there are times when
you want to explicitly add the const, to control overload
resolution, or template instantiation, for example.
Isn't that what static_cast is for? const_cast sounds like the
wrong tool for the job (because common C++ wisdom dictates
that static_cast is good and const_cast should usually be
avoided if possible).
That's a good point. As Pete said, const_cast is for adjusting
const, and that's what you're doing. But IMHO, it's arguable
both ways:
-- If you use static_cast, you can't accidentally add const
(but is this really a problem?). Also, it won't show up if
someone greps for const_cast (which they're doubtlessly
doing to find "dangerous" code, and adding const isn't
dangerous).
-- If you use const_cast, you can't accidentally perform a
Derived* to Base* (or worse, a Base* to Derived*) conversion
which you didn't want.
IMHO, that second point predominates, and is, ultimately, the
reason why the new style casts were introduced: const_cast
allows adjusting const-ness, with no risk of accidentally
performing any other conversion, static_cast allows moving up
and down in the hierarchy, without any risk of accidentally
removing const-ness or type punning, and reinterpret_cast forces
type punning (even if the types involved are pointers within an
inheritance hierarchy), without any risk of removing const-ness.
You may as well say "if you want to add constness eg. for
overload resolution, use reinterpret_cast". That's just wrong.
Agreed. Using static_cast or reinterpret_cast to adjust
const-ness, even when they allow it (i.e. adding const) is just
wrong.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34