suggestion: read-only array-reference

Ben Phillips Ben_member at pathlink.com
Thu Jul 20 07:52:50 PDT 2006


In article <e9o0pm$2j03$1 at digitaldaemon.com>, Johan Granberg says...
>
>Dave wrote:
>>> While I'm all for a built in const I disagree with the last paragraph. 
>>> I don't want the compiler to try to prevent me subverting the 
>>> protection by using casts or pointer tricks (c++ had const cast for a 
>>> reason). I have used some c++ libraries where some values where const 
>>> when not strictly needed, and I was able to achieve the desired 
>>> behavior by the use of a cast. (This is of course unsafe and should 
>>> never bee used in library code, just in quick and dirty applications 
>>> or internally in your own code base where you can use this as a shortcut)
>> 
>> And I disagree with that <g> If const was not strictly needed (or could 
>> not easily be subverted w/o asm as you can w/ C++) then the C++ library 
>> you mention should not have used it. With some sort of "true const" D 
>> libraries would be written differently.
>
>I agree with you about the library beeing incorrectly written. But 
>notice this line in my reply.
>
> >> or internally in your own code base where you can use this as a 
>shortcut)
>
>the case when you have a class like this
>
>class Foo
>{
>	const char[] name;
>	void setName(const char[] c){(cast(char[])name)[]=c;}
>}
>
>this could bee achieved by using properties but I think this should bee 
>allowed.

Well, in your case, why declare "name" as a "const" if you intend to allow it to
be modified? A const member in a class should only be allowed to be modified in
a constructor of that class.

Off-topic:
If D gets const then I think the following would be a nice piece of syntatic
sugar:

char[] str = "hell";
str ~= 'o'; // I can modify it
someFunc(const str); // that function can't

I dunno, it looks nice to me :P





More information about the Digitalmars-d mailing list