suggestion: read-only array-reference
Hasan Aljudy
hasan.aljudy at gmail.com
Thu Jul 20 14:00:19 PDT 2006
Ben Phillips wrote:
> 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
>
>
That's how my suggestion sort of works:
You have a normal-reference to the array.
BUT,
You can pass a read-only reference of the array to functions.
so, if someFunc is declared to take a read-only reference, then the
following:
char[] str = "hell";
str ~= "o"; //ok, normal reference
someFunc( str ); //str is implicitly converted to a read-only reference
for the function
//OR
someFunc( str.readonly ); //explicitly convert it to a read-only reference
str ~= " world"; //ok: for you, it's still a normal reference.
More information about the Digitalmars-d
mailing list