Constants, Aliases

Don Clugston dac at nospam.com.au
Thu Dec 14 06:04:34 PST 2006


Lutger wrote:
> Hasan Aljudy wrote:
>>
>>
>> Lutger wrote:
>>> Alexander Panek wrote:
>>>> Lutger wrote:
>>>>> Xinok wrote:
>>>>>> The problem with the const keyword is it doesn't guarantee the 
>>>>>> expression will
>>>>>> be constant.
>>>>>
>>>>> It doesn't? How can you modify a const var then? (in D)
>>>>
>>>> You can modify const variables that are not set directly at 
>>>> declaration (write-once constants) just by getting their address and 
>>>> modifying them through another variable/pointer.
>>>
>>> Haha yes it works. Is that how it should be or is it a bug or 
>>> compiler limitation? It looks whacky to me. You can only write a 
>>> const once in a constructor or so says DMD, thus it seems like this 
>>> subverts the system in more than one way. I can't imagine that ever 
>>> being useful.
>>
>> Why not?
>> It's useful when you work with sane programmers.
>>
>> After all, with pointers and asm, there's no limit to how many things 
>> you can mess.
> 
> Sure, if you want it you can break the type system. But there are some 
> barriers for pointers, these are still typed. I don't think it is so 
> obscure.
> If you have a const value type in a class, you must set it in the 
> initializer or the constructor. You also cannot modify it. Fine, but 
> then if you have a getter return a reference to it, suddenly all bets 
> are off.
> This is not what I'd expect, probably because of a C++ bias I still have 
> somewhere, that I (wrongly) think const is part of the type system?

The confusion comes from the way that D uses const in two ways.
const XXX = YYY;
really is const, cannot be changed (even in theory), and probably won't 
appear in the executable at all. This is definitely part of the type system.

const XXX;
is not const at all (it's a variable!). 'final' might have been a better 
name. As you mention, the read-only protection seems to be very fragile.
It seems a very hard thing to enforce.



More information about the Digitalmars-d mailing list