Casting away const
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 9 08:04:40 PDT 2010
On Mon, 09 Aug 2010 10:53:48 -0400, BCS <none at anon.com> wrote:
> Hello Steven,
>
>> On Mon, 09 Aug 2010 10:37:14 -0400, BCS <none at anon.com> wrote:
>>
>>> Hello Steven,
>>>
>>>> On Mon, 09 Aug 2010 10:11:39 -0400, Don <nospam at nospam.com> wrote:
>>>>
>>>>> Steven Schveighoffer wrote:
>>>>>
>>>>>> On Sun, 08 Aug 2010 17:56:25 -0400, simendsjo
>>>>>> <simen.endsjo at pandavre.com> wrote:
>>>>>>> I'm totally new to the const/immutable thing, so this might be a
>>>>>>> naive question..
>>>>>>> The spec says:
>>>>>>> "modification after casting away const" => "undefined behavior"
>>>>>> I thought it was "you're on your own", not undefined behavior.
>>>>>> The
>>>>>> former implies there is some "right" way to do this if you know
>>>>>> more
>>>>>> about the data than the compiler, the latter implies that there is
>>>>>> no
>>>>>> right way to cast away const. Am I wrong?
>>>>>> -Steve
>>>>> I think you're wrong. It's OK to cast away const, as long as you
>>>>> don't
>>>>> modify the thing which is supposed to be const.
>>>>> But if you modify it, there's no way the compiler can guarantee
>>>>> that
>>>>> your code will work. Anything could happen.
>>>> But then what is the point of casting away const? If you are not
>>>> going to modify it, then there is no reason to cast it away.
>>>>
>>> There are some cases where non-const pointers are used but never
>>> modified (C api's for instance) cast as always is just a way subvert
>>> the type system where it gets in your way.
>>>
>> C's api can be modified at declaration. It has no mangling, so you
>> can type it how it should be (if C had const). For example:
>> extern(C) int strlen(const(char)* str);
>> I find that much more pleasant than having to cast away const.
>
> OTOH that is effectively a hidden cast and has 100% of the same issues
> (re undefined behavior) as casting away const while being slightly
> harder to find.
But you just said that casting and reading is not undefined? Isn't this
the same thing?
Const is such a strange beast because it plays no role in code generation,
it's effectively only a tool to help the compiler decide what is
possible. It doesn't occupy any space or translate whatsoever to the
underlying code.
I think there are definite good uses for writing to const or immutable
data besides ones that can be stored in ROM. That is, if you are sure a
const or immutable piece of data is on the heap/stack, it should be
reasonable to be able to modify it for performance gains.
-Steve
More information about the Digitalmars-d-learn
mailing list