Extended Type Design.
Andrei Alexandrescu (See Website For Email)
SeeWebsiteForEmail at erdani.org
Fri Mar 16 02:25:24 PDT 2007
Derek Parnell wrote:
>>> int a;
>>> const! int* p = &a; // error! cannot convert int* to const! int*
>>> final int b = 42;
>>> const! int* p1 = &b; // yah, b is truly immutable
>>> const! int* p2 = new const! int; // yah
>
> I'm not sure about that last one. Does this mean that p2 points to an int
> that cannot change and p2 itself can no longer be changed? And what is the
> value in the int that p2 points to?
Good point. There is a little exception here. People expect that when
they write:
const char[] str = "Hi!";
they can't modify str nor its characters. So they expect str to be final
as well. We then arrange that if const appears in a data definition,
that data is automatically made final as well. So the above is
equivalent to:
final const char[] str = "Hi!";
If you don't want str to be final, do this:
const(char[]) str = "Hi!";
> Can you do this sort of thing ...
>
> int x = 5;
> const! int* p2 = new const! int(x);
>
> meaning that p2 now points to a 'final' int whose value is 5, plus p2 can
> never be changed now either.
Yes, you can.
>> ... and return values: "const char[] immutableTextProp()" ?
>
> Hmmmm... does "const char[] X" mean that X.ptr can change, X.length can
> never change and the data pointed to by X.ptr can never change? Or is "can
> never" too strong? Is it more that code within the scope of the declaration
> is not allowed to change those things?
See the exception above. But now consider a function:
void say(const char[] data)
{
...
}
The bits of data are a private copy of say, so they can be changed
discretionarily (if that's a word). But the bits pointed to by data do
not belong to say, so they can't be written.
If say wants to be fancy, it can look like this:
void say(final const char[] data)
{
...
}
Then data can't be even rebound. The "final" being a storage class, it
doesn't appear in the function signature (e.g., in the interface file).
Andrei
More information about the Digitalmars-d
mailing list