Topic: reinterpret_cast<> and discarding const


Author: John Max Skaller <maxtal@suphys.physics.su.oz.au>
Date: 1995/11/19
Raw View
Greg McGary <gkm@magilla.cichlid.com> wrote:
>C++ Std sez (draft std and all recent WPs) in 5.2.9 (2) `The
>reinterpret_cast operator shall not cast away constness.'
>
>Unfortunately, whereas this might be possible to enforce for a single
>reinterpret_cast<>, a sequence of two can easily discard
>cv-qualifiers:
>
>    char const *const *const *const ccpcpcpc;
>    char *** cppp;
>    cppp = reinterpret_cast<char ***> (reinterpret_cast<int> (ccpcpcpc))
>
>Nasty.
>
>Does a conforming compiler have any responsibility to detect this hole
>(seems doable, but definitely a hassle), or is it just an unfortunate
>wart?

  The rule against reinterpret_cast<> casting away constness
is NOT enforceable in general because it is clearly
meaningless in many cases.

  The reason _certain_ specific cases are required to be
caught is simply to provide that little extra bit of help
to programmers.

  int const *pci;
  reinterpret_cast<unsigned*>(pci); // fine, NO error

  Reinterpret cast allows you to change the TYPE of a pointer!
Throwing away constness is only a very special case of that,
and it's actually inconsistent to not permit it.

  So the "wart" is the rule that you can't cast away constness
with a reinterpret cast, not the fact that you can.

--
John Max Skaller               voice: 61-2-566-2189
81 Glebe Point Rd              fax:   61-2-660-0850
GLEBE NSW 2037                 email: maxtal@suphys.physics.oz.au
AUSTRALIA                      email: skaller@maxtal.com.au
---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]