readonly storage class

Benjamin Thaut code at benjamin-thaut.de
Sun Apr 8 09:09:48 PDT 2012


Am 08.04.2012 11:49, schrieb Simen Kjaeraas:
> On Sun, 08 Apr 2012 11:39:03 +0200, Benjamin Thaut
> <code at benjamin-thaut.de> wrote:
>
>> Am 08.04.2012 11:28, schrieb Jonathan M Davis:
>>> On Sunday, April 08, 2012 11:16:40 Benjamin Thaut wrote:
>>>> While typing D code I usually come across the problem that neither
>>>> const
>>>> nor immutable describe the usage pattern of the memory I'm currently
>>>> working on 100%. Sometimes I have immutable data that has been shared
>>>> among threads that I want to pass to a function. Then I have some const
>>>> data that I want to pass to the same function. Currently you don't have
>>>> any other choice but to write that function two times. But the function
>>>> itself does not need the "extended" properties of const or immutable:
>>>>
>>>> const: can be casted back to mutable
>>>> immutable: can be implicitly shared among threads
>>>>
>>>> The only thing the function cares about is, that it will not change the
>>>> data passed to it. It would be kind of nice to have a thrid storage
>>>> class "readonly". It can not be casted back to mutable and it can
>>>> not be
>>>> implicitly shared among threads, but both const and immutable
>>>> implicitly
>>>> convert to readonly, because both of these storage classes lose one of
>>>> their properties during conversion. That way you only have to write the
>>>> function once and can pass both const and immutable data to it.
>>>>
>>>> Just an idea, comments and critics welcome.
>>>
>>> I would point out that casting const to mutable and then altering the
>>> variable
>>> is subverting the type system. The compiler does not support casting
>>> away
>>> either const or immutable to alter _anything_. So, as far as the type
>>> system
>>> is concerned, if you want a function that takes both const and
>>> immutable, it
>>> should take const.
>>>
>>> Now, you _can_ cast away const and alter a variable if you're
>>> careful, but
>>> you're subverting the type system when you do so and throwing away any
>>> guarantees that the compiler gives you. It's far from safe.
>>>
>>> Given that casting away const on a variable and then mutating is
>>> subverting
>>> the type system and thate therefore the compiler is free to assume
>>> that you
>>> will never do it, I don't see what your idea of readonly would buy
>>> us. It's
>>> the same as const.
>>>
>>> - Jonathan M Davis
>>
>> I'll come up with a example.
>> But if what you say is true, why is immutable not implicitly
>> convertible to const?
>
> It is.

Thanks, then this is a misunderstanding on my side, and this topic is 
irrelevant. But what about calling const methods on immutable objects?

-- 
Kind Regards
Benjamin Thaut


More information about the Digitalmars-d mailing list