[cfe-commits] Better const_cast support

Eli Friedman eli.friedman at gmail.com
Fri Sep 26 12:09:40 PDT 2008


On Fri, Sep 26, 2008 at 8:26 AM, Sebastian Redl
<sebastian.redl at getdesigned.at> wrote:
> Next I'll take a closer look at the beast that makes
> int i;
> const int &ri = i;
> fail to compile :-)

References are tricky... good luck getting them working well.

> +  // If we end up with constant arrays of equal size, unwrap those too. A
> cast
> +  // from const int [N] to int (&)[N] is invalid by my reading of the
> +  // standard, but g++ accepts it even with -ansi -pedantic.
> +  const ConstantArrayType *SrcTypeArr, *DestTypeArr;
> +  if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) &&
> +     (DestTypeArr = Context.getAsConstantArrayType(DestType)))
> +  {
> +    if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
> +      // Different array sizes.
> +      Diag(OpLoc, diag::err_bad_const_cast_generic,
> +        OrigDestType.getAsString(), OrigSrcType.getAsString());
> +      return false;
> +    }
> +    SrcType = Context.getCanonicalType(SrcTypeArr->getElementType());
> +    DestType = Context.getCanonicalType(SrcTypeArr->getElementType());
> +  }

This just seems completely strange to me... it does seem reasonable,
but the standard pretty clearly doesn't allow it.  I guess
compatibility trumps the standard, though; this seems to be pretty
universally supported.

Although, does your code deal with the following case correctly?
const int* ar[100] = {0};
int* (*par)[100] = const_cast<int*(*)[100]>(&ar);

> +  // Since we're dealing in canonical types, the remainder must be the
> same.
> +  // FIXME: These must not be function or member function types.

This one is a little tricky... you have to watch out for cases where
the const gets cast off of a pointer type rather than the function
type.

-Eli



More information about the cfe-commits mailing list