Is this a desing rationale? (static array object member)
Regan Heath
regan at netmail.co.nz
Sun Sep 30 04:47:07 PDT 2007
Janice Caron wrote:
> On 9/30/07, janderson <askme at me.com> wrote:
>> sections like [1,1,1,1,1] would be marked as const somehow in the GC (or
>> somewhere). If a modification occurs it would make a call to dup the
>> first time.
>
> This is all solved in D2.0, so really it's a non-issue.
>
> int[] x = [1,1,1,1,1]; /* won't compile */
As you've discovered, actually it will. This however wont (in D 2.0):
char[] x = "test";
and that is because string literals are invariant(char). I made a
suggestion in another thread that array literals should be invariant(T)
as well, then you would get the behaviour you describe below.
> const(int)[] x = [1,1,1,1,1]; /* OK, but now you can't accidently
> modify the array */
>
> int[] x = [1,1,1,1,1].dup; /* OK */
>
> The fact that the first version won't compile is precisely why const
> correctness is a good thing. Without const, there's nothing to stop
> you typing that line of code into a program and hitting undefined
> behavior, and not even realising it. const saves the day.
Not "const" specifically but "invariant" which indicates data which can
never ever change (even if nasty pointer tricks are used - and these
will likely cause a seg fault).
This differs (as I'm sure you're aware) from "const" which is a
read-only view of data which may change via another reference/pointer/etc.
Note; I am referring to D 2.0's current const implementation.
Note; I realise that you know all this I replied for the benefit of
others :)
Regan
More information about the Digitalmars-d
mailing list